3

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?

Daryl1976
  • 675
  • 2
  • 8
  • 20
  • So you want to be notified only once what all the `this._accountsService.removeFromClientLibrary` calls complete? – martin Nov 08 '16 at 07:32

1 Answers1

1

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));
Meir
  • 14,081
  • 4
  • 39
  • 47