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?

1
  • So you want to be notified only once what all the this._accountsService.removeFromClientLibrary calls complete? Commented Nov 8, 2016 at 7:32

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.