Reputation: 86
I have a series of Http calls that are made by looping through the gadgets. Is there a way to abort all the requests
for (let gadget of gadgets) {
this.userService.getGadgetsData(gadget.Id, gadget.Name).subscribe(gadgetsData => {
});
}
My service code in component.service.ts
@Injectable()
export class UserService {
constructor(public _http: Http) { }
getGadgetsData() {
return this._http.get(this._dashboards, { headers: this.getHeaders() })
.map((res: Response) => res.json());
}
}
Upvotes: 4
Views: 2715
Reputation: 1760
Please take a look if this is what you want.
observableList: [];
......
for (let gadget of gadgets) {
let obs = this.userService.getGadgetsData(gadget.Id, gadget.Name).subscribe(gadgetsData => {
});
this.observableList.push(obs);
}
...
onClick() {
for (let i = 0; i < this.observableList.length; i++) {
this.observableList[i].unsubscribe();
}
}
Upvotes: 6
Reputation: 1035
You can add timeout for your request, and then unsubscribe
from your observables.
Note: I'm assumming you're using RxJs and Observable because of your sample code.
If you have a click event, you can save a reference to all your observables (inside your loop
) and put them in a list, and then inside your function (e.g. onClick()
) iterate through that list and unsubscribe
from all your Observables.
var myObservable = this.userService.getGadgetsData(gadget.Id, gadget.Name)
.subscribe(gadgetsData => {});
//later on your code, maybe on your click event
myObservable.unsubscribe();
From the github docs: unsubscribe and subscribe
Trying to be thorough:
You can also add Observables to other Observables, so that when you unsubscribe from the main (parent) observable all observable contained within will also unsubscribe. You can achieve it with the methods add
and remove
contain in the Observable object.
There could be a better way to do this, but that's off top of my head.
Upvotes: 0