路由器的决心不会注入控制器 [英] Router resolve will not inject into controller

查看:124
本文介绍了路由器的决心不会注入控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经想尽一切办法让UI路由器的决心,传递它的值给定的控制器AppCtrl。我使用依赖注入 $注,这似乎引起问题。我缺少什么?

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?

路由

$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;
      });
    }],
  }
});

控制器

appControllers.controller('AppCtrl', AppCtrl);

AppCtrl.$inject = ['$scope', '$rootScope'];

function AppCtrl($scope, $rootScope, auser) {
  var vm = this;
  console.log(auser); // undefined

  ...
}

修改
这里有一个普拉克 http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=$p$ PVIEW

推荐答案

当您使用路线的决心参数作为绑定到该路由控制器依赖注入,您不能使用NG-控制器指令,控制器,因为与服务提供商名称 aname 不存在。它是一个动态的依赖由路由器时,它实例在各自的局部视图要绑定的控制器注入。

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.

还记得返回 $超时在你的榜样,因为它返回一个承诺,否则你的观点将得到没有任何价值解决,同样的是,如果你使用的情况下 $ HTTP 或返回一个承诺的其他服务。

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.

  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;
}

在视图,而不是NG-控制器,使用用户界面视图指令:

in the view instead of ng-controller, use ui-view directive:

<div ui-view></div>

演示

Demo

这篇关于路由器的决心不会注入控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆