两次实例化Angular2延迟加载服务 [英] Angular2 Lazy Loading Service being Instantiated Twice

查看:142
本文介绍了两次实例化Angular2延迟加载服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚将应用程序切换为今天可以延迟加载.
我有一个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中).原因是延迟加载的模块获取其 own 服务实例.如果希望该服务真正是单例,则将其仅添加到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屋!

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