简体   繁体   English

Angular 4共享服务可观察到的行为主题

[英]Angular 4 Shared Service Observable Behavior Subject

I have an BehaviorSubject as part of a SharedServices Module that is provided to the AppModule in the Providers section of the module and subscribe to it in the AppComponent. 我有一个BehaviorSubject作为SharedServices模块的一部分,该模块在Providers部分提供给AppModule,并在AppComponent中进行订阅。 I also subscribe to it in another component that is part of another Module AdminModule but I'm not getting the changes unless I add it to it Providers section of the AppComponent. 我还在另一个模块AdminModule的另一个组件中订阅了它,但是除非将其添加到AppComponent的Providers部分中,否则我不会获得更改。 Why is this? 为什么是这样? I thought if you add it to the Providers section in the Module and subscribe all subscribers would get the changes? 我以为如果将其添加到模块的“提供者”部分并订阅所有订阅者,将获得更改?

I have to do this for the child components to get the changes. 我必须对子组件执行此操作才能获取更改。 I'm really confused by this. 我对此很困惑。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers : [ AppsSharedService]    <--------

You might want to follow the guidance of the Angular docs and move this global provider out of that "shared" module and into a "core" module: 您可能需要遵循Angular文档的指导,并将此全局提供程序移出该“共享”模块并移入“核心”模块:

https://angular.io/guide/ngmodule#no-shared-module-providers https://angular.io/guide/ngmodule#no-shared-module-providers

I suspect what's happening here is the service is created twice, so changes that are happening in one aren't reflected in all. 我怀疑这里发生的事情是该服务创建了两次,因此一次发生的更改不会全部反映出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM