Mike Mike - 2 months ago 29
AngularJS Question

api call on init and params change

I am attempting to make an api call based on params using angular2. I need to make this api call when the component is initialized and when the params change. Below is the code I am using. The problem is when

ngOnInit
is run it calls the api with the params and then immediately subscribes to changes which calls the api 2 more times.

What is the proper way to handle this sort of situation so that the api call is only called once on init while still being able to observe changes to the params?

ngOnInit() {
Observable.zip(this.route.queryParams, this.route.params).subscribe((params: any) => {
this.queryParams = params[0];
this.params = params[1];
this.get();
this.subscribe();
});
}

subscribe() {
this.queryParamsSub = this.route.queryParams.subscribe((params: any) => {
this.queryParams = params;
this.get();
});

this.paramsSub = this.route.params.subscribe((params: any) => {
this.params = params;
this.get();
});
}

// this is called 3 times on init
get() {
this.apiManager.get(this.queryParams, this.params);
}

ngOnDestroy() {
this.queryParamsSub.unsubscribe();
this.paramsSub.unsubscribe();
}

Answer

It turns out that you can use Observable.combineLatest to combine the observables and this will trigger on every change. Something like this works nicely:

  ngOnInit() {
    this.sub = Observable.combineLatest(this.route.queryParams, this.route.params).subscribe((params: any) => {
      this.queryParams = params[0];
      this.params = params[1];
      this.get();
    });
  }
Comments