0

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?

3 Answers 3

1

you can just replace the conditional logic with this line

   let class$= classId?this.classService.getById(classId):of(null)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is very silly of me.. I should have seen this, not sure what I was thinking. Probably tried to overthink this simple stuff.
1

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);

1 Comment

Thank you. It was very silly of me to not see this also since @Fan Cheung answered first so I accepted that answer but I will upvote your answer as well
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.