If my API is not returning data in let's say 5 seconds I have to call another one. I tried to achieve it like this:
this.service.returnData1(param1, param2)
.pipe(timeout(5000), finalize(() => this.callSecondApi()))
.subscribe(
data => {
this.myList = data.filter(item => !this.removeStuffFromList(item, data));
if (this.myList.length > 0) {
//do some other stuff
this.originalList = this.myList;
}
},
(err) => {
console.log(err.message);
}
)
callSecondApi(){
this.service.returnData2(param1, param2).subscribe(
data1 => {
this.myList = data1.filter(item => !this.removeStuffFromList(item, data1));
}
if (this.myList.length > 0) {
this.originalList = this.myList;
}
},
(err) => console.log(err.message)
)
}
What is the best approach to solve this ? I also tried different answers with switchMap, tap, mergeMap but nothing seemed to work mostly because I have to add that timeout on the first subscribe. Thanks !
CodePudding user response:
You should probably not use finalize
, since you only want to switch to observe the second API call once the first one has failed (or timed out). Therefore you should just use catchError
operator to switch to another observable:
this.service
.returnData1('param1', 'param2')
.pipe(
timeout(5000),
catchError((err) => callSecondApi())
)
.subscribe({
next: (data) => {
console.log(data);
},
error: (err) => {
console.log(err.message);
},
});
Note: Passing separate functions to a subscribe
call is deprecated. I instead used an observer object.