【问题标题】:Angular 2 and rxjs subject in service isn't being update on component服务中的 Angular 2 和 rxjs 主题未在组件上更新
【发布时间】:2017-02-18 13:04:24
【问题描述】:

大家好,提前感谢您的帮助... 我正在构建一个应用程序,我想要一个用于处理某些配置的服务,它由不同的模块共享。 我真的不知道这是否是最好的方法,但我从 angularJS 开始使用它。

配置服务

sidebarCompress: Subject<boolean> = new Subject<boolean>();
public sidebarCompressed: Observable<boolean> = this.sidebarCompress.asObservable();

constructor() {}

compressSidebar(val: boolean = false) {
    this.sidebarCompress.next(val);
    // this is firing when used
    console.log('changed on service');
}

侧边栏组件

constructor(
    private conf: ConfigService,
) {
    conf.sidebarCompressed.subscribe(
        sidebarCompressed => {
            // this is not firing
            console.log('changed on sidebar component');
    });
}

任何其他组件

constructor(
    private conf: ConfigService,
) { }

ngOnInit() {
    // The idea is to use it in a fn (not always on init)
    this.conf.compressSidebar(true);
}

所以,侧边栏组件订阅不起作用,任何人都知道我在这里做错了什么,或者我是否应该采取不同的方法!?

再次,非常感谢。

【问题讨论】:

  • 你们在哪里提供ConfigService
  • 每个模块中都提供了ConfigService。在这种情况下,我有一个模块,其中有 SidebarComponent 和一个延迟加载的模块,该模块使用试图压缩侧边栏的组件调用。两个模块都提供了ConfigService...我也在app.module 中提供了它...

标签: javascript angular typescript observable subject


【解决方案1】:

如果您在 @NgModule() 中提供服务,您将获得整个应用程序的单个实例,除非您还在 @Component() 或延迟加载模块的 @NgModule() 中提供它。

@NgModule() 中提供的提供程序被提升到应用程序根注入器中,其中模块的导入顺序很重要,如果提供程序键匹配,imports: [] 中稍后列出的模块将覆盖以前的模块提供程序。 AppModules @NgModule() 中添加的提供程序直接覆盖导入模块的提供程序。

延迟加载的模块有自己的“根作用域”,它是应用程序根注入器的子注入器。

我认为您的问题是由于在非延迟加载的延迟加载的模块中提供服务引起的,这会导致 2 个实例。

注入此模块的组件或服务从应用程序根目录获取实例(如果它们是非延迟加载模块的一部分),或者从延迟加载模块获取实例(如果它们是延迟加载模块的一部分)。

作为解决方案,从延迟加载的模块中删除提供程序。 也可以实现forRoot(),在AppModule中导入MyLazyLoadedModule.forRoot(),将延迟加载模块的服务引入应用根注入器,避免重复服务实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多