user3356007
user3356007

Reputation: 403

Angular call a function after 2 http calls are finished

I am using angular4 what I want to achieve is that a function is called after 2 or 3 calls are finished.

example:

  this.Get.firstGet().subscribe( data=> {

               this.test();
          });

  this.Get.secondGet().subscribe( data=> {

               this.test();
          });

  test(){
    //do something when firstGet and secondGet are both finished

   }

thx for the help!

Upvotes: 0

Views: 1242

Answers (2)

Ashish Ranjan
Ashish Ranjan

Reputation: 12950

You are separately calling this.test(); in each subscribe() so by your code you are calling it twice.

I believe what you want is forkJoin, this will only execute the success, error blocks when all the Observables are resolved

forkJoin(this.Get.firstGet(), this.Get.secondGet()).subscribe(([firstGet, secondGet]) => {
    this.test();
})

Upvotes: 1

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You can use combineLatest from RxJS to wait all inner observables to fire at least once

import { combineLatest } from 'rxjs';
...


combineLatest(
   this.Get.firstGet(),
   this.Get.secondGet()
)
.subscribe(([responseOfFirst, responseOfSecond]) => {
     this.test();
})

Or you can use forkJoin as well: https://www.learnrxjs.io/operators/combination/forkjoin.html

Upvotes: 1

Related Questions