0

How can I call my methods from component only after multiple service call is completed?

I have a service.ts file which has one method that will return the array with different values based on the key (i.e. obj here) as shown below:-

getdata(type:numer)
 {
   // make a post call to get the data
 }

Here, in component.ts file, I have two methods which will call the above service method as shown below:- These 2 methods are used to fill the dropdown in html when clicked on edit form button

method1()
{
   this.service.getdata().subscribe((res: any) => {
      data1 = res;
    });
}

method2()
{
   this.service.getdata().subscribe((res: any) => {
      data2 = res;
    });
}

I have one more method which will fill the form data on edit click

fillForm()
{
    // do something
}

Now, my requirement is I need to call method1 and method2 in component.ts and also I need to call this fillForm method only after above two methods are completed as I need to make sure the dropdown should be filled before editing the form

1
  • Have you tried adding callback() functions so that when a method completes the callback() is called and you know that method1 has finished Commented Aug 31, 2018 at 12:25

1 Answer 1

2

Hello if you are using rxjs 5 you can use Observable zipping :

Observable.zip(
    this.method1(),
    this.method2()
).subscribe(
    ([dataFromMethod1, dataFromMethod2]) => {
        // do things
    },
    (error) => console.error(error),
    () => {
        // do things when all subscribes are finished
        this.fillform();
    }
)

With rxjs 6, simply change Observable.zip by forkJoin :

forkJoin(
    this.method1(),
    this.method2()
).subscribe(
    ([dataFromMethod1, dataFromMethod2]) => {
        // do things
    },
    (error) => console.error(error),
    () => {
        // do things when all subscribes are finished
        this.fillform();
    }
)

You will need to change your methods to return Observables :

method1()
{
   return this.service.getdata();
}

method2()
{
   return this.service.getdata();
}
Sign up to request clarification or add additional context in comments.

3 Comments

zip is not parallel, it's like a zipper on a jacket, one after the other until completed, combineLatest, merge and forkJoin are acceptable alternatives.
In rxjs 5, using Observable.zip make parallel calls. However, I agree with your comment for rxjs6, that's why I used forkJoin
Note that this.fillform() will not be executed when any of the Observables throws an error. Source: reactivex.io/documentation/operators/subscribe.html. For things you need to do whether there are errors or not, you should use .finally()

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.