【问题标题】:angularjs ui-router issue with resolveangularjs ui-router问题与解决
【发布时间】:2015-10-12 20:19:04
【问题描述】:

我正在使用 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 代码: 获取配置文件:函数(){ 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),并且注入的依赖项的值是 undefined,如控制台所述。记录通话。

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

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

那么,这里会发生什么?

提前感谢您的任何回答。

【问题讨论】:

  • getProfile 的代码在哪里?模板中是否还有ng-controller
  • 我的模板上没有 ng-controller 指令,因为在状态定义中我为状态公开了控制器。 getProfile() 的代码非常简单。我已经编辑了我的问题并添加了代码
  • 对,只是检查一下控制器,因为同时使用两者并不少见

标签: javascript angularjs


【解决方案1】:

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

例如

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

【讨论】:

  • 不需要,因为如果你在数组上指定了用户 profile_dependency,那么 angularjs 会抛出一个异常,指出未找到 user_profile 提供程序。 resolve 自动注入依赖。
  • @asolenzal 不,您需要阵列中的所有注射并以正确的顺序进行
  • @asolenzal 你不正确。如果 Angular 抛出该错误,那么这就是您的实际问题可能是什么的线索......
  • 对,你是对的,我的朋友,解决了问题.... +1 并为你回答标记
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 2015-05-12
相关资源
最近更新 更多