-1

I am working on a component, where I need to call two APIs parallelly. And I want to call a method only when both the API calls are resolved.

ngOnInit() {
    this.serviceOne.someApi().subscribe((res) => {
        this.response1 = res;  
    });
    this.serviceTwo.someApi().subscribe((res) => {
        this.response2 = res;  
    });
}

I want to call a method only when this.response1 and this.response2 is getting populated.

Currently, I am wrapping the logic inside the method with an if statement.

someMethod() {
    if(this.response1 && this.response2) {
        //logic
    }
}

and putting someMethod() inside subscribe() of both the api calls.

What is the best way to achieve this?

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

3

You can use forkJoin to achieve it.

Try like this:

Working Demo

  ngOnInit() {    
    const request1 = this.serviceOne.someApi();
    const request2 = tthis.serviceTwo.someApi();

    forkJoin([request1, request2]).subscribe(data => {
      this.response1 = data[0];
      this.response2 = data[1];
      this.someMethod();
    });
  }
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

same answer with array destructuring.

forkJoin([
  this.serviceOne.someApi(),
  this.serviceTwo.someApi(),
]).subscribe(data => {
    let [serviceOneResponse, serviceTwoResponse] = data;
    // use responses.
});
Dharman
  • 30,962
  • 25
  • 85
  • 135
Metinerk
  • 39
  • 5