2

I have a service written that sends some data to an API request. However, i need to call it multiple times depending on how many checkboxes a user clicked. What is the best way to do this? I was looking into Observables forkJoin method but am not sure how to implement it.

Here is how i currently call the service (without loop):

this.myService.update(id, data).subscribe(
    data => { 
        console.log('Data: ', data);
    },
    error => { console.log('Error: ', error }
);
4
  • Please add your html Commented Nov 3, 2016 at 17:09
  • @PatrickJane There is no HTML for this scenario. Just a bunch of ids in an array that i need to loop over and call this service method in it. Commented Nov 4, 2016 at 7:52
  • Where is the checkboxes Commented Nov 4, 2016 at 9:20
  • 1
    They are part of another component. I just get the checked ids passed to me in an array. Commented Nov 4, 2016 at 12:47

1 Answer 1

8

Okay i found a way to do it:

let observables = new Array();

for( let id of ids ) {
    observables.push(this.myService.update(id, data));
}

Observable.forkJoin(observables).subscribe(
    res => console.log(res),
    error => console.log('Error: ', error)
);

Basically i made an array of the service i needed to execute in parallel and then passed it to forkJoin. When all the observables are complete, the response is passed into the res argument of the subscribe method.

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.