Angular2 Observable BehaviorSubject service not working

断了今生、忘了曾经 提交于 2019-11-29 05:38:54

Every time you emit a value, you should create a new object instead of emitting the same mutated object. That will protect you from change detection issues. It'd be better to always assign a new Object to this.keys when you change it though.

this.data.next([...this.keys]);

You can use asObservable() here

public getData(): Observable<number[]> {
  return this.data.asObservable();
}

Also check for what Günter Zöchbauer said. Are you providing the service as a singleton?

I faced the same issue at some point. It's likely the reason is that your service is not a singleton, i.e. that every subscriber gets a new instance. Contrary to Angular 1, in A2 services are not singletons.

If you want to have one instance of the service shared by multiple services/components, put it in providers of your parent @Component or @NgModule.

@NgModule({
  declarations: [],
  imports: [],
  bootstrap: [AppComponent],
  providers: [DataService]
})
export class AppModule {
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!