简体   繁体   中英

Angular2: Cancel Http requests that are in a loop

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

}

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

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM