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

Mik*_*ika 6 angularjs angular-ui-router angular-fullstack

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

这是路线:

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

这是组件:

(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: '<'
      }
    });

})();
Run Code Online (Sandbox Code Playgroud)

使用Angular 1.5和yeoman angular-fullstack

Mul*_*ary 4

您需要执行以下操作之一

  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;
      }
    }
});
Run Code Online (Sandbox Code Playgroud)

方法 #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();
});
Run Code Online (Sandbox Code Playgroud)

对方法 #2 的进一步解释:

每个作用域都$scope将从$rootScopeso long继承$rootScope.user,指向一个实际对象,子作用域将指向同一个对象。

The best practice if you choose to go with #2 is to bind the user object to a property of a defined object on the $rootScope to avoid any issues:

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

But then you'll have to update your template to use data.user.

EDIT:

I've found this example in the docs, might shed a bit of light on the issue:

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('...'); }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 这个答案太棒了。我错过了这样一个事实:路由的控制器应用于模板,并且与也具有控制器的组件呈现的内容是分开的。 (2认同)