Angular2 延迟加载服务被实例化两次 [英] Angular2 Lazy Loading Service being Instantiated Twice
问题描述
我今天刚刚将我的应用程序切换为延迟加载.
我有一个 SharedModule
可以导出一堆服务.在我的 AppModule
中,我导入了 SharedModule
,因为 AppComponent
需要访问一些共享服务.
I just switched my application over to be lazy-loaded today.
I have a SharedModule
that exports a bunch of services.
In my AppModule
, I import SharedModule
because AppComponent
needs access to a few of the shared services.
在另一个模块 FinalReturnModule
中,我导入了 SharedModule
.在我的一项服务中,我在构造函数中放置了一个 console.log('hi')
.
In another module FinalReturnModule
, I import SharedModule
. In one of my services, I put a console.log('hi')
in the constructor.
当应用程序首次加载时,我将 hi
发送到控制台.每当我导航到 FinalReturnModule
中的页面时,我都会再次收到 hi
.显然,由于有两个实例,因此模块无法通信,因此无法正常工作.
When the app first loads, I get hi
to the console. Whenever I navigate to a page within the FinalReturnModule
I get hi
again. Obviously, since there are two instances, nothing's working correctly since the modules aren't able to communicate.
如何阻止服务被实例化两次?
How can I stop the service from being instantiated twice?
背景,应用程序是使用 angular-cli 构建的.
Background, the app is built using angular-cli.
当前版本:
angular-cli: 1.0.0-beta.24
node: 6.9.1
os: win32 ia32
@angular/common: 2.4.1
@angular/compiler: 2.4.1
@angular/core: 2.4.1
@angular/forms: 2.4.1
@angular/http: 2.4.1
@angular/platform-browser: 2.4.1
@angular/platform-browser-dynamic: 2.4.1
@angular/router: 3.1.1
@angular/compiler-cli: 2.4.1
推荐答案
如果服务真的是一个单例(创建一次),不要将它添加到任何模块中,因为它会成为懒惰的一部分——加载的模块(例如在 SharedModule
中).原因是延迟加载的模块获得了它们自己 的服务实例.如果您希望该服务成为真正的单例,则只需将其添加到 AppModule
,或将仅导入到 AppModule
的核心模块".或者你可以使用 forRoot
,它只会在 AppModule
If the service is truly meant to be a singleton (one created once), don't add it to any module that will be a part of a lazy-loaded module (e.g. in the SharedModule
). The reason is that lazy-loaded module get their own instances of services. If you want the service to be truly a singleton, then add it just to the AppModule
, or the "Core Module" that will get imported only to the AppModule
. Or you can use forRoot
which will only be called in the AppModule
import { ModuleWithProviders } from '@angular/core';
@NgModule({
declarations: [...],
imports: [...]
})
class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [ MySingletonService ]
}
}
}
@NgModule({
imports: [ SharedModule.forRoot() ]
})
class AppModule {}
@NgModule({
imports: [ SharedModule ]
})
class OtherModule {}
现在 AppModule
是唯一一个使用提供程序导入模块的模块.
Now the AppModule
is the only module that imports the module with the providers.
另见:
- 模块文档.所有这些内容都在那里进行了解释.
- Docs on Modules. All this stuff is explained there.
这篇关于Angular2 延迟加载服务被实例化两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!