Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 making multiple requests using rxjs subscribe

I have an angular2 app that adds or removes items from a multiple select box and sends each item to a remote api individually to be added to be processed in the database. The following method sends the request to the server and gets a response as an observable

removeFromClientLibrary(username: string, roleID: string): Observable<any> {
        let body = JSON.stringify({Key: username, Value: roleID});

        return this._http.post(this._removeFromLibraryURL, body, this.emsConfig.getStandardHttpHeaders())
            .map((res:Response) => <any>res.json());
    }

Then I have added a client to consume this, by using the subscribe method to consume it. My understanding is that it is only necessary to call subscribe once, however, I can't seem to get this to work. The only thing that returns the proper result is to loop through each item and subscribe multiple times:

for (let i = 0; i < selected.length; i++) {
  this._accountsService.removeFromClientLibrary(this.username, selected[i].RoleID)
    .subscribe(status => {          
      console.log(status);
    });
}

Is there a way to consume the results of the api using rxjs without subscribing multiple times as above, or is that the only way to retrieve the data?

like image 789
Daryl1976 Avatar asked Nov 17 '25 15:11

Daryl1976


1 Answers

You can use the combineLatest operator.

Observable.combineLatest(
  selected.map(selectedId =>
    this._accountsService.removeFromClientLibrary(this.username, selected[i].RoleID)))
)
  .subscribe((statusArray) => console.log('all done: ', statusArray));
like image 160
Meir Avatar answered Nov 19 '25 08:11

Meir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!