Angular2 Observable BehaviorSubject service not working

后端 未结 2 1642
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 12:20

I\'m trying to create my own observable service but after i get the initial data from the service, any updates to the service aren\'t propagated to any subscribers. Service

相关标签:
2条回答
  • 2020-12-16 12:20

    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?

    0 讨论(0)
  • 2020-12-16 12:43

    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 {
    }
    
    0 讨论(0)
提交回复
热议问题