繁体   English   中英

AngularJS UI路由器问题与解决

[英]angularjs ui-router issue with resolve

我正在使用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:function(){var d = $ 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调用所述。

我已经调试了代码,并且可以在服务器上获取用户配置文件的服务运行良好,因此,在那里没有问题。 即使我在user_profile解析键上使用对象返回,该错误仍然存​​在。

另一件事是,如果我在状态定义上将controller属性设置为状态定义中定义的函数,则将依赖项注入正确的值,但是我不希望这样做,而是希望将依赖项注入到定义的内联控制器上的controller no也是如此。

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

预先感谢您的任何答复。

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

例如

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM