I encountered a situation where I needed to make sequential API calls using RxJs
in Angular
. However, despite successfully implementing the calls, I am struggling with a null error. In this scenario, the second API call depends on receiving an id
from the first API, which may be either null
or undefined
. My objective is to return of(null)
if the id is not available, otherwise return the response. Unfortunately, TypeScript errors have emerged in my current implementation. Below is what I have accomplished thus far:
of(personId).pipe(
take(1),
switchMap((personId: string) => {
return this.personService.getById(personId).pipe(
concatMap((person: Person) => {
const classId = person?.class?.id || null;
let class$ = of(null);
if (classId) {
class$ = this.classService.getById(classId); // Will return Observable<Class>
}
return combineLatest([of(person), class$])
})
)
}),
tap(([person, class]) => {
console.log('Person: ', person);
console.log('Clas: ', class);
})
).subscribe()
class$ = this.classService.getById(classId);
Within this line, I am encountering the error 'TS2322: Observable is not assignable to Observable`
Do you have any suggestions on how I can resolve this issue? Additionally, do you believe there are ways in which this code could be improved?