Angular 2 http get observable called twice
In English, when you subscribe to a stream (Observable
) the code inside the first function inside the subscribe block will be executed when that observable emits data.
If you subscribe twice it will be called twice, etc
Since you are subscribing multiple times the first function (called the next function) inside the subscribe block will be executed multiple times.
You should only subscribe to a stream once inside ngOnInit
.
When you want to emit data onto the stream, you could use an RXJS Subject for this and make the Subject subsequently emit to the stream you are subscribed to using RXJS flatmap.
Your subscribe
should be put in the component instead of the service. Reason being your component is subscribed to the data returned from the service, and later on you can unsubscribe or add more control (such as denounce) if needed. The code will look like this after the changes.
In your component:
ngOnInit() {
this.loadData();
}
loadData(){
this._service.getData().subscribe(data => this.pages = data);
}
In you service:
getData() {
return this.http.get('./src/data.json')
.map((res:Response) => res.json());
}
this._service.getData()
returns a Subject, not a PageContent list. You could change your loadData
like :
loadData() {
this._service.getData().subscribe(data => this.pages = data);
console.log("Load data !");
}
and remove the subscribe
part of your getData
method (from DemoService
). I've just tested this, and the ngOnInit
is called once