Problem Statement: Currently I have a frontend application which has 5 graphs In a page (Each Graph have a different endpoint to fetch the data) to be rendered based on the data retrieved from the database, and I have a dropdown which updates the charts based on the value selected from the drop-down.
Now In the frontend the graphs will be loaded with default values and My requirement is that whenever users select any dropdown and if any HTTP calls(from the default values) running I want to cancel them and make new request(The main reason because sometimes the data from the previous request takes longer than latest data which is selected from the drop-down hence my graphs are still updated with old request instead of new value selected from the dropdown as I could see from the Chrome Network Tab ,Old Request gets finished after the latest request hence graph updates with old request) and all these graphs makes parallel request to these methods to render the data.
With help of @Amit Chigadani currently I have the below function written in service but with this approach, the endpoints from even the latest request getting canceled and graphs are not rendered at all, can you please help me with the approach
In the Service
getData(url: string) {
const finalRequest = new RequestModel(this.myModel);
const body = JSON.stringify(finalRequest);
const headers = new Headers({ "Content-Type": "application/json" });
const options = new RequestOptions({ headers: headers });
return this.http.post(url, body, options).switchMap((res) => {
const resp = res.json();
return Observable.of(resp);
});
}
In the Component
public mySub: Subscription;
if (this.mySub !== undefined) {
this.mySub.unsubscribe();
}
this.mySub = this.myService.getData(this.url).subscribe((data) => {
try {
}
catch (err) {//do something if error
}
return this.mySub;
});
Versions
- Angular : 4.0.1
- rxjs : 5.0.3