• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

153
Vistas
Sequential API call using Rxjs in Angular with null return

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?

over 3 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

you can just replace the conditional logic with this line

   let class$= classId?this.classService.getById(classId):of(null)
over 3 years ago · Santiago Trujillo Denunciar

0

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);
over 3 years ago · Santiago Trujillo Denunciar

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.

over 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda