解决Angularjs ui-router问题

angularjs ui-router issue with resolve

本文关键字:问题 ui-router Angularjs 解决      更新时间:2023-09-26

我正在创建一个应用,使用angularjs和angular-ui-router进行基于状态的路由。我的应用程序中有几条路线,但其中一条需要注意。状态定义如下

state('profile', {
            url: '/profile',
            controller: 'ProfileController', //controller on a different file
            resolve: {
                user_profile: ['User', function (User){
                    return User.getProfile(); //returns a json object
                }]
            },
            templateUrl: 'profile.html'
        })

getProfile代码:getProfile:函数(){Var = $q.defer();

            $http.get('/profile')
                .success(function(res){
                    if (res.status == 'success'){
                        d.resolve(res);
                    } else {
                        d.reject();
                    }
                })
                .error(function(reason){
                    d.reject(reason);
                });
            return d.promise;
        }
现在,在我的控制器文件中,我有以下代码:
.controller("ProfileController", ['$scope',function($scope,user_profile){
    console.log(user_profile);
}]);

问题是resolve应该在一个名为user_profile的参数上注入解析的结果(因为在状态定义的键中我使用了user_profile),并且注入的依赖项有一个由console.log调用声明的undefined值。

我已经调试了我的代码,并且在服务器上获取用户配置文件的服务工作得很好,所以,在那里没有问题。即使我在user_profile解析键上使用对象返回,错误仍然存在。

另一件事是,如果我在状态定义中设置了控制器属性为状态定义中定义的函数,那么依赖项就会被注入正确的值,但我不希望这样,我希望依赖项也注入到已定义的控制器上,而不是内联控制器上。

那么,这里会发生什么呢?

提前感谢任何答案。

您正在使用angular的严格DI语法(依赖项名称的字符串数组,函数作为数组的最后参数),但您没有在数组中指定user_profile依赖项。

.controller("ProfileController", ['$scope','user_profile',function($scope,user_profile) { console.log(user_profile); }]);