javascript - UI路由器: understanding resolve promises flow of the root-sub states

标签 javascript angularjs promise angular-ui-router angular-promise

我正在使用 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');
            });
        }
    }
})

但输出与我的预期不同:

enter image description here

最佳答案

在您的示例中,“app.my-calls”确实是在“app”状态之后创建的(您可以通过记录 onEnter 回调来验证这一点。)

From Ui-router wiki

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/

相关文章:

javascript - 如何将动态范围变量添加到angularjs中的for循环?

javascript - 如何将集合传递给 angular.js 中的指令?

javascript - AngularJS 中发生路由更改时如何设置 ngclass 更改?

node.js - 在模块加载和配置期间使用 Nodejs Promises (Bluebird)

javascript - Twitter 告诉我错误未找到卡(卡错误)

基于Javascript的图像编辑工具canvas或SVG

javascript - 5 秒后使用 javascript 使所有图像具有相同的 id 可见

javascript - Chrome扩展程序动态添加脚本

javascript - 使用 catch 是否需要 throw

javascript - 如何进行条件 promise 链