Why rxjs concat operator is not working as expected?

Viewed 43

I used concat to chain two API calls, the second call uses the response of the first call.

The problem is that when I try to console.log() the response of the First Call I get undefined. and it says in the console that the first call is being made before the second call.

enter image description here

dataFromFirstCall: any
  constructor(private http: HttpClient) {
    concat(
      this.firstCall(),
      this.secondCall(this.dataFromFirstCall)
    ).subscribe()
  }

getResponse() {
  return this.http.get('assets/dummyData.json').pipe(tap(data => {
     console.log('First call')
     this.dataFromFirstCall=data;
   })
  )
}

secondCall(response: any) {
   console.log(response, 'Second call')
   return this.http.get('assets/dummyData2.json')
}
1 Answers

concat() is the wrong method to use. You'll want to use switchMap() to pass the result down the pipe. Using a local instance variable dataFromFirstCall is not what you want to do.

If you only need the result from the second call, you don't need a subscription, keep it as an observable and bind to it in your template using the async pipe to get the value.

@Component({
  ...
})
class YourComponent {
  data$: Observable<any>;

  constructor(private http: HttpClient) {
    this.data$ = this.firstCall().pipe(
      switchMap(response => this.secondCall(response))
    );
  }

  private firstCall() {
    return this.http.get('assets/dummyData.json');
  }

  private secondCall(response: any) {
    // do stuff with response
    return this.http.get('assets/dummyData2.json');
  }
}
<another-component data="data$ | async"></another-component>
Related