将 CoreModule 导入另一个组件模块时存在多个主题

问题描述 投票:0回答:1

因此,在我的 app.component 中包含每个页面上的标头(在 app.module 中导入的 CoreModule)以及基于路由加载模块的 app-routing.module (在本例中为 SomeContainerRoutingModule)

问题是,当我尝试将属于 CoreModule 一部分的 DropdownComponent 导入到容器中时,它将主题视为单独的对象,并且不包含标头中找到的可观察对象。当我从导入中排除 CoreModule 时,Subject 工作正常,但 DropdownComponent 不再出现在页面上。

如何使用相同的主题/服务,同时将核心组件添加到页面? CoreModule 不应该已经从标头所在的根 app.component 导入吗?

核心模块

...
declarations: [HeaderComponent, DropdownComponent],
providers: [MessageService]
export class CoreModule {}

一些容器路由模块

...
imports:[...
//CoreModule
//removing this makes Subject work. Adding it makes the component appear
...

消息服务

export class MessageService {
private subject = new Subject<any>();
sendMessage(message){this.subject.next(message);}
getMessage(){return this.subject.asObservable();}
}

我尝试将核心组件添加到容器模块的导入中,但出现错误:类型 DropdownComponent 是 2 个模块声明的一部分:CoreModule 和 SomeContainerRoutingModule!... 我也尝试过将服务添加到容器模块,但它似乎没有影响任何东西。

javascript angular typescript rxjs
1个回答
0
投票

似乎您希望 MessageService 在应用程序中是单例的。

在这种情况下,最好不要在任何地方提供它,只需在 MessageService @Injectable 装饰器中添加providedIn:'root',如下所示:

@Injectable({
  providedIn: 'root'
})
export class MessageService {
private subject = new Subject<any>();
sendMessage(message){this.subject.next(message);}
getMessage(){return this.subject.asObservable();}
}

然后它将在您的所有组件中提供,并且它将是单例的。只需确保从所有模块提供程序数组中删除 MessageService(不要在核心模块或其他任何地方提供它)。否则,如果您在某些惰性模块中提供它,例如您的 SomeContainerRoutingModule ,那么该模块将为该服务拥有自己的注入器,并且它将创建一个新实例。

这里有关于 angualr 中依赖注入如何工作的非常详细的文档:https://angular.io/guide/hierarchical-dependency-injection

© www.soinside.com 2019 - 2024. All rights reserved.