使用UI路由器解析并传递给组件的控制器 [英] Resolve using UI Router and pass to a component's controller
问题描述
使用组件时,如何使用UI Router解析变量。
How do I resolve a variable with UI Router when I am using a component.
这是路线:
$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
Using Angular 1.5 and yeoman angular-fullstack
推荐答案
您将需要执行以下操作之一:
You will need to do one of the following:
- 为状态创建一个控制器,并将解析的值绑定到
$ scope
。 - 绑定
Auth.getCurrentUser()
到$ rootScope
,使其可在每个州使用。
- Create a controller for the state and bind the resolved value to the
$scope
. - Bind the reference of
Auth.getCurrentUser()
to the$rootScope
for it to be available for each state.
方法1的示例:
Example for approach #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的示例:
Example for approach #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的进一步解释:
Further explaination on approach #2:
每个 $ scope
都将从 $ rootScope
继承,因此只要 $ rootScope.user
指向实际对象,子作用域将指向同一对象。
Each $scope
will inherit from $rootScope
so as long $rootScope.user
points to an actual object, child scopes will point to the same object.
如果您选择转到 best #2的用途是将用户对象绑定到 $ rootScope
上已定义对象的属性,以避免出现任何问题:
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...
}
});
但是您必须更新模板以使用 data.user
。
But then you'll have to update your template to use data.user
.
编辑:
我在文档中找到了这个示例,可能对这个问题有所了解:
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('...'); }
}
});
});
这篇关于使用UI路由器解析并传递给组件的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!