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
您需要执行以下操作之一:
$scope.Auth.getCurrentUser()到 ,$rootScope使其可用于每个状态。.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)
.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)
| 归档时间: |
|
| 查看次数: |
2600 次 |
| 最近记录: |