简体   繁体   English

Angular ui-router 解析继承

[英]Angular ui-router resolve inheritance

I would like to create an abstract parent state, that has only one job: to resolve the current user through an ajax server call, and then pass this object to the child state.我想创建一个抽象的父状态,它只有一项工作:通过 ajax 服务器调用解析当前用户,然后将此对象传递给子状态。 The problem is that the child state never gets loaded.问题是子状态永远不会被加载。 Please have a look at this plunker: Example请看看这个plunker:示例

a state一个state

angular.module('test', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider){

    // Parent route
    $stateProvider.state('main', {
      abstract:true,
      resolve: {
        user: function(UserService){
          return UserService.getUser();
        }
      }
    });

    // Child route
    $stateProvider.state('home', {
      parent: 'main',
      url: '/',
      controller: 'HomeController',
      controllerAs: '$ctrl',
      template: '<h1>{{$ctrl.user.name}}</h1>'
    });

    $urlRouterProvider.otherwise('/');
  });

a factory factory

angular.module('test').factory('UserService', function($q){
  function getUser() {
    var deferred = $q.defer();

    // Immediately resolve it
    deferred.resolve({
      name: 'Anonymous'
    });

    return deferred.promise;
  }

  return {
    getUser: getUser
  };
});

a controller controller

angular.module('test').controller('HomeController', function(user){
  this.user = user;
});

In this example, the home state will never display the template, I don't really understand why.在这个例子中, home状态永远不会显示模板,我真的不明白为什么。 If I remove the parent: 'main' line, then it displays the template, but of course I get an error because it cannot find the user dependency in the HomeController .如果我删除parent: 'main'行,那么它会显示模板,但当然我会收到错误,因为它在HomeController找不到user依赖项。

What am I missing?我错过了什么? I did everything like it is described in ui-router's documentation, I think this should work.我做了 ui-router 文档中描述的所有事情,我认为这应该可行。

Every parent must have a target ui-view in template for its child每个父级都必须在其子级模板中具有目标 ui-view

$stateProvider.state('main', {
  abstract:true,
  resolve: {
    user: function(UserService){
      return UserService.getUser();
    }
  }
  template: '<div ui-view=""></div>'
});

NOTE: Another option is to use absolute names and target index.html .. but in this case the above is the way to go ( Angularjs ui-router not reaching child controller )注意:另一种选择是使用绝对名称和目标 index.html .. 但在这种情况下,上面是要走的路( Angularjs ui-router 没有到达子控制器

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

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