Home > Enterprise >  Sequential API call using Rxjs in Angular with null return
Sequential API call using Rxjs in Angular with null return

Time:04-11

I have a scenario where I need to make a sequential API call using RxJs in Angular, which I have done but I am facing this null error. For calling the 2nd api I will receive and id from the first API which can be null or undefined. So what I wanted to If if id is not available I will return of(null) otherwise will return the response. But there are some typescript error. Following is what I have done so 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);

On this line I am facing the 'TS2322: Observable is not assignable to Observable`

Any suggestion on how do I resolve this? Also can this code be improved?

CodePudding user response:

you can just replace the conditional logic with this line

   let class$= classId?this.classService.getById(classId):of(null)

CodePudding user response:

The observable that is returned by this.classService.getById is different to the one that is returned by of(null), hence you cannot reassign the class$ variable with it.

However your problem can easily be overcome by simply using a ternary operator to define class$ as follows:

const class$ = person?.class?.id ? this.classService.getById(classId) : of(null);

CodePudding user response:

First of all this of(personId) it seems weird.

Why not:

this.personService.getById(personId).pipe(
  concatMap((person: Person) => {
    const class$ = person?.class?.id
      ? this.classService.getById(person?.class?.id)
      : of(null);
    return combineLatest([of(person), class$]);
  })
).subscribe(/*...*/);

The error TS2322: Observable is not assignable to Observable I think that it is self-described.

  • Related