Sta*_*lfi 3 javascript ngrx angular
Angular2-RC5。
The modules need to have the same instance of the service. To accomplish this, the service needs to be in the providers of your bootsrap AppModule only. Otherwise, if the same service is found in different providers, you could be running parallel instances.
So the question becomes: how to get the service in the top-level providers, but exclude it from all other modules?
With a service you write yourself, it's really straightforward.
AppModule, pt it in that module's providers and nowhere elseDummyModule) of yours that you're importing into other modules, make sure to not put it in DummyModule's providers or an Angular injector will create a parallel instance of it for every lazy-loaded module that imports DummyModule. Instead, you want to expose that service from a forRoot() static method. So change:
@NgModule({
providers: [ MyService]
})
export class DummyModule{ }
Run Code Online (Sandbox Code Playgroud)
To:
@NgModule({
providers: [] //empty since we want a singleton service
})
export class DummyModule{
static forRoot() {
return {ngModule: DummyModule, providers: [ MyService ]};
}
}
Run Code Online (Sandbox Code Playgroud)
Now when regular modules imports: [DummyModule], they will not get MyService. On the other hand, in AppModule, you have imports: [DummyModule.forRoot()] which exposes the service. As a result, only the top-most component gets the service and you'll have a single instance of it shared among all modules.
With a 3rd party service, it's not straightforward.
基本上,如果它也使用@NgModule. 或者,您可以创建一个自定义模块,而不是导入第 3 方模块,该模块声明该模块的组件、管道和指令,但实施上述更改以将该模块的服务放入一个forRoot()方法中。
这就是我为了让 3rd 方服务MdIconService(Angular Material 模块的一部分)作为单个实例工作而做的事情,即使其模块尚未正确配置。请参阅此 github 问题。
| 归档时间: |
|
| 查看次数: |
624 次 |
| 最近记录: |