本文介绍了存储用于组件的注入器实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 RC5 之前,我使用 appref 注入器作为服务定位器,如下所示:

Before RC5 I was using appref injector as a service locator like this:

启动.ts

bootstrap(...)
.then((appRef: any) => {
    ServiceLocator.injector = appRef.injector;
});

ServiceLocator.ts

ServiceLocator.ts

export class ServiceLocator {
    static injector: Injector;
}

组件:

let myServiceInstance = <MyService>ServiceLocator.injector.get(MyService)

现在在 bootstrapModule().then() 中做同样的事情不起作用,因为组件似乎在承诺之前开始执行.

Now doing the same in bootstrapModule().then() doesn't work because components seems to start to execute before the promise.

有没有办法在组件加载之前存储注入器实例?

Is there a way to store the injector instance before components load?

我不想使用构造函数注入,因为我在由许多组件派生的基础组件中使用注入器,我宁愿不将注入器注入所有组件.

I don't want to use constructor injection because I'm using the injector in a base component which derived by many components and I rather not inject the injector to all of them.

推荐答案

我已经设法使用手动 boostrapping 来做到这一点.不要在 @NgModule 中使用bootstrap: [AppComponent]"声明,而是使用 ngDoBootstrap 方法:

I've managed to do it using manual boostrapping. Don't use "bootstrap: [AppComponent]" declaration in @NgModule, use ngDoBootstrap method instead:

export class AppModule {
    constructor(private injector: Injector) {
    }

    ngDoBootstrap(applicationRef: ApplicationRef) {
        ServiceLocator.injector = this.injector;
        applicationRef.bootstrap(AppComponent);
    }
}

这篇关于存储用于组件的注入器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:52