我正在使用 ui - 路由器开发 Angular 应用程序。
我创建了根状态,这是一个旨在解决异步问题的抽象状态。依赖关系。
因此,从我的 Angular 来看,每个子状态都应该能够在自己的解析状态属性中使用这些依赖项。
因此,如果abstract
根状态解决异步依赖关系,而子状态也解决异步依赖关系,则后者应该等待根依赖关系解决,然后再启动自己的resolve
方法。对吗?
这是代码示例,它说明了我的意思:
在相应的解析中使用基于异步、基于 promise 的方法
public iAmInTheRootState(): IPromise<any> {
let deferred = this._$q.defer();
this._$timeout(() => {
deferred.resolve();
}, 3000);
return <IPromise<any>> deferred.promise;
}
public iAmInTheSubState(): IPromise<any> {
let deferred = this._$q.defer();
this._$timeout(() => {
deferred.resolve();
}, 100);
return <IPromise<any>> deferred.promise;
}
根抽象状态:
$stateProvider
.state('app', {
url: '/',
abstract: true,
templateUrl: 'layout/app-view.html',
resolve: {
auth: function (Auth: IAuthService) {
'ngInject';
return Auth.iAmInTheRootState().then(() => {
console.log('I am the root state, so I should be first');
});
}
}
});
子状态,即子状态:
$stateProvider.state('app.my-calls', {
url: '',
controller: 'MyCallsController',
controllerAs: '$ctrl',
templateUrl: 'states/my-calls/my-calls.html',
resolve: {
secondAuth: (Auth: IAuthService) => {
'ngInject';
return Auth.iAmInTheSubState().then( () => {
console.log('although I am faster I should be second because i am in the sub state');
});
}
}
})
但输出与我的预期不同:
最佳答案
在您的示例中,“app.my-calls”确实是在“app”状态之后创建的(您可以通过记录 onEnter 回调来验证这一点。)
Resolve
You can use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.
解析回调不是用来延迟状态创建的,而是用来延迟 Controller 创建的。
要了解完整流程,您可以记录 $stateChangeStart 和 $stateChangeSuccess 事件。
关于javascript - UI路由器: understanding resolve promises flow of the root-sub states,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084165/