使用 UI 路由器解析并传递给组件的控制器

Resolve using UI Router and pass to a component's controller

如何在使用组件时使用 UI 路由器解析变量。

这是路线:

$stateProvider
  .state('route', {
    url: '/route',
    template: '<my-component user="user"></my-component>',
    resolve: {
      user: (Auth) => {
        return Auth.getCurrentUser().$promise;
      }
    }
  })

这是组件:

(function () {

   class BookingListComponent {
     constructor(user) {
        //I want to use the user here but getting the unknown provider error
     }

  }

  angular.module('app')
    .component('myComponent', {
      templateUrl: 'my-url.html',
      controller: MyComponent,
      bindings: {
      user: '<'
      }
    });

})();

使用 Angular 1.5 和 yeoman angular-fullstack

您需要执行以下一项

  1. 为状态创建控制器并将解析值绑定到 $scope
  2. Auth.getCurrentUser() 的引用绑定到 $rootScope 以供每个州使用。

方法 #1 的示例:

.state('route', {
    url: '/route',
    template: '<my-component user="user"></my-component>',
    controller: ($scope, user) => { $scope.user = user; },
    resolve: {
      user: (Auth) => {
        return Auth.getCurrentUser().$promise;
      }
    }
});

方法 #2 的示例:

.run(($rootScope, Auth) => {
 //This does NOT replace the resolve in your state definition but for this to work,
 //Auth.getCurrentUser() must NEVER return null.
 $rootScope.user = Auth.getCurrentUser();
});

关于方法 2 的进一步解释:

每个 $scope 都将从 $rootScope 继承,因此只要 $rootScope.user 指向一个实际对象,子范围将指向同一个对象。

如果您选择使用#2,最佳 做法是将用户对象绑定到 $rootScope 上已定义对象的 属性避免任何问题:

.run(($rootScope, Auth) => {
     $rootScope.data = {
      //Now user can be null.
      user: Auth.getCurrentUser()
      //Other shared data...
     }
});

但是您必须更新模板才能使用 data.user

编辑:

我在文档中找到了这个例子,可能会阐明这个问题:

angular.module('myMod', ['ngRoute']);
.component('home', {
  template: '<h1>Home</h1><p>Hello, {{ $ctrl.user.name }} !</p>',
  bindings: {
    user: '<'
  }
})
.config(function($routeProvider) {
  $routeProvider.when('/', {
    //Notice $resolve?
    template: '<home user="$resolve.user"></home>',
    resolve: {
      user: function($http) { return $http.get('...'); }
    }
  });
});