Send request which depends on other request Angular

40 views Asked by At

I read about Angular rxjs operators but didn't understand how can change my logic to send request to server which depends on other request and its data.

I have a modal window open and on ngOnInit I send a couple of request some of them are connected together. I haven't use any of the rxjs operators when sending my requests.

It's like:

getMyCompanyDetails(){
 this.companyService.getCompany('my company name').subscribe(
  data => {
  .... there is logic I implement with response data, which will depends on the second request
 }
}

My goal is to send sequentially requests which depends on each other. The second will wait unitl the first one is ready. I read about it with different approaches with switchMap, concatMap and etc. but I have diffuclty in implementing it. Please help me with the best pattern (solution) which has to be used in that case. Thank you!

1

There are 1 answers

0
cvb On

The switchMap operator will allow you to handle the response but will require you to return a new observable. Use this to return an observable based on the response from your call to 'getCompany'. You would then subscribe to this new observable to access its response.

getMyCompanyDetails(){
 this.companyService.getCompany('my company name').pipe(switchMap((data) => { 
   if (data) {
     return someObservable;
   } 

   return otherObservable;
 })).subscribe((resultOfInnerObs) => { /* do something */ })

I would recommend taking a look at the documentation and examples on https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap