Sheetal
Sheetal

Reputation: 3

How to call multiple http service in parallel from angular component

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

Upvotes: 0

Views: 3295

Answers (1)

Augustin R
Augustin R

Reputation: 7819

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();
}

Upvotes: 2

Related Questions