Angular2: Cancel Http requests that are in a loop

I have a series of Http calls that are done by looping through the gadgets. Is there a way to abort all 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());
    }

}

      

+3


source to share


2 answers


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();
    }
}

      

+4


source


You can add timeout for your request and then unsubscribe

from your observables.

Note. I assume you are using RxJs and Observable because of your sample code.

If you have a click event, you can keep a reference to all of your observables ( inside your loop

) and put them in a list, and then inside your function (for example onClick()

), pass that list and unsubscribe

from all of your observers.

    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 observables contained within will also be unsubscribed. You can achieve this with methods add

and remove

in the Observable.

There might be a better way to do this, but it's off my head.

0


source







All Articles