延迟Angular应用程序启动,直到承诺解决? [英] Delaying Angular application start until promise resolves?

查看:56
本文介绍了延迟Angular应用程序启动,直到承诺解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有这个:

new Loader().load().then(() => {
    platformBrowserDynamic().bootstrapModule(AppModule);
  });

问题在于,我不一定要延迟一切,直到诺言得以解决,只需 ngOnInit 和任何路由解析.我想允许IS N'T路由或渲染的任何其他angular2设置,但是将其阻止,直到承诺解决为止.有没有更有效的方法可以做到这一点?

The problem is that I don't necessarily need to delay everything until the promise resolves, just ngOnInit and any route resolving. I'd like to allow any other angular2 setup that ISN'T routing or rendering, but block those until a promise resolves. Is there a more efficient way to do this?

推荐答案

使用APP_INITIALIZER

第一种选择是使用 APP_INITIALIZER .通过此操作,您可以在 AppComponent 被引导之前进行初始工作:

First option would be to use the APP_INITIALIZER. With this you can do initial stuff, before the AppComponent gets bootstrapped:

@NgModule({
    // ...
    providers: [
        {
            provide: APP_INITIALIZER, 
            useFactory: appInitFactory, 
            deps: [AppInitService],
            multi: true
        }
    ]
})
export class AppModule {}

使用 deps 数组,您可以在工厂内部注入您可能需要的服务:

With the deps array you can inject services you might need inside your factory:

export function appInitFactory(appInitService: AppInitService): () => Promise<any> {
    return () => appInitService.initializeApplication();
}

您必须与此一起返回一个(箭头)函数.

You have to return an (arrow) function with this.

使用路由器配置

第二个选项,如果您使用 Router ,则是在initialNavigation 设置为 false angular.io/api/router/RouterModule#forRoot"rel =" nofollow noreferrer>在 RouterModule 上调用 forRoot :

Second option, if you use the Router is to set the initialNavigation to false in your forRoot call on the RouterModule:

@NgModule({
    imports: [
       RouterModule.forRoot(AppRoutes, {initialNavigation: false})
    ]    
})
export class AppModule {}

然后在您的 AppComponent 内部,您应该具有一些服务,该服务可以为您执行 Promise 逻辑,并在完成操作后导航到您想去的地方.此解决方案的问题"是 AppComponent 确实已初始化,但是如果您只考虑实际的路由并不能立即解决,而是在等待解决,您可以使用此

Then inside your AppComponent you should have some service which does the Promise logic for you, and navigate where you want to go after its done. The 'problem' with this solution is that the AppComponent does get initialised, but if you only mind about the actual routes not getting resolved immediately, but do have sort of an app-shell while you wait for the resolving, you can use this

这篇关于延迟Angular应用程序启动,直到承诺解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆