I am building a website with Angular2 that consists of multiple pages containing a dashboard with various statistics.
On a single page, 6 different requests are made separately (one for each dashboard tile), which can take up to 5 seconds to conclude. The problem appears when I change the page whilst the requests for the dashboard are ongoing.
On this situation, the requests will start to stack up, and if I change the page multiple times the dashboards will take more and more time to be loaded. Each request is made the following way:
return this.http.post("http://mywebsite.com/dashboard/info", body, options)
.map((res) => {
return res.json()
}).subscribe((result) => { /* do something */});
What I am looking for is for a way to abort all of the ongoing requests when I change the page, to avoid that they stack up and cause excessive loading times.
When you call subscribe
an Subscription
object is created and it persists until the observable is completed.
You have to unsubscribe
from the post request when you no longer need the result. The most common way is to call unsubscribe
from ngOnDestroy
of a component.
/** * Disposes the resources held by the subscription. May, for instance, cancel * an ongoing Observable execution or cancel any other type of work that * started when the Subscription was created. * @return {void} */ unsubscribe(): void;
EDIT:
Note that is you call share()
, take()
, first()
or any other operator that creates a new observable than unsubscribing will not cancel the HTTP request. As you'll be unsubscribing from a child observable only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With