我今天刚刚将应用程序切换为懒人装载
我有SharedModule
导出一堆服务。
在我的AppModule
中,我导入SharedModule
因为AppComponent
需要访问一些共享服务。
在另一个模块FinalReturnModule
中,我导入SharedModule
。在我的一项服务中,我在构造函数中添加了console.log('hi')
。
首次加载应用时,我会hi
到控制台。每当我导航到FinalReturnModule
中的某个页面时,我再次获得hi
。显然,由于有两个实例,因为模块无法通信,所以没有任何工作正常。
如何阻止服务实例化两次?
编辑:背景,应用程序是使用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
答案 0 :(得分:16)
如果该服务确实是一个单独的(一个创建一个),请不要将它添加到任何将作为延迟加载模块的一部分的模块中(例如在AppModule
中)。原因是延迟加载的模块获得了自己的服务实例。如果您希望服务真正成为单身人士,请将其仅添加到AppModule
或“核心模块”,该核心模块将仅导入forRoot
。或者您可以使用仅在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
现在HashMap<String, String>
是唯一通过提供商导入模块的模块。
另见: