路由器解析不会注入控制器 [英] Router resolve will not inject into controller
问题描述
我已经尝试了一切来让 ui-router 决心将它的值传递给给定的控制器——AppCtrl.我正在使用 $inject
依赖注入,这似乎会导致问题.我错过了什么?
路由
$stateProvider.state('app.index', {网址:'/我',templateUrl: '/includes/app/me.jade',控制器:'AppCtrl',控制器为:'vm',解决: {用户:['用户',功能(用户){返回 User.getUser().then(function(user) {返回用户;});}],}});
控制器
appControllers.controller('AppCtrl', AppCtrl);AppCtrl.$inject = ['$scope', '$rootScope'];函数 AppCtrl($scope, $rootScope, auser) {var vm = 这个;控制台日志(用户);//不明确的...}
编辑这是一个 plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview
当你在绑定到路由的控制器中使用路由解析参数作为依赖注入时,你不能使用带有 ng-controller 指令的控制器,因为具有name aname
不存在.它是一个动态依赖,由路由器在实例化控制器时注入到其各自的局部视图中.
还要记住在您的示例中返回 $timeout
,因为它返回一个承诺,否则您的参数将在没有值的情况下得到解决,如果您使用 $http
或其他返回承诺的服务.
即
解析:{用户:['$超时',函数($超时){返回 $timeout(function() {返回{名称:'我'}}, 1000);}],
在控制器中注入解析依赖.
appControllers.controller('AppCtrl', AppCtrl);AppCtrl.$inject = ['$scope', '$rootScope','auser'];//在这里注入用户函数 AppCtrl($scope, $rootScope, auser) {var vm = 这个;vm.user = auser;}
在视图而不是 ng-controller 中,使用 ui-view
指令:
I have tried everything to get ui-router's resolve to pass it's value to the given controller–AppCtrl. I am using dependency injection with $inject
, and that seems to cause the issues. What am I missing?
Routing
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: 'AppCtrl',
controllerAs: 'vm',
resolve: {
auser: ['User', function(User) {
return User.getUser().then(function(user) {
return user;
});
}],
}
});
Controller
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope'];
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
console.log(auser); // undefined
...
}
Edit Here's a plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview
When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname
does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.
Also remember to return $timeout
in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http
or another service that returns a promise.
i.e
resolve: {
auser: ['$timeout', function($timeout) {
return $timeout(function() {
return {name:'me'}
}, 1000);
}],
In the controller inject the resolve dependency.
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
vm.user = auser;
}
in the view instead of ng-controller, use ui-view
directive:
<div ui-view></div>
这篇关于路由器解析不会注入控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!