Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Angular2 Observable BehaviorSubject service not working

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 looks like this:

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs/Rx';

@Injectable()
export class DataService {
  keys : number[] = [4,5,1,3,2];
  private data :BehaviorSubject<number[]> = new BehaviorSubject(this.keys);

  constructor() {};

  public setKey(i:number, val:number) :void {
    this.keys[i]=val;
    this.data.next(this.keys);
  }
  public getData() :Observable<number[]> {
    return new Observable(fn => this.data.subscribe(fn));
  }
  public getKeys() :number[] {
    return this.keys;
  }
}

the component using the service gets the initial data just fine. that component gets its data in the constructor:

constructor(public dataService: DataService) {
    dataService.getData().subscribe(data => {
      console.log("Gotcha!");
      this.data.datasets[0].data = data)
    });
};

which gives one Gotcha in the console log. But after updating the data with setKey(2,3) somewhere else, i was expecting the this.data.next(this.keys); to send data to all subscribers and data would be updated inside that component accordingly. but no data is sent to the subscribers..

i thought i figured the Observables out but please dont be friendly if i'm missing the point here ;) any pointers in the right direction will be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...