问题
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. 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. 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] <--------
回答1:
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:
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.
来源:https://stackoverflow.com/questions/47098986/angular-4-shared-service-observable-behavior-subject