简体   繁体   中英

How to avoid nested subscriptions with concatMap in Angular

I get an array of products with this code

 proyecto$:Observable<Proyecto>
 this.proyecto$=this.http.get<ProjectApi>(`${this.urlProyecto}/${this.proyectoId}`)
.pipe(
  map(p => <Proyecto>{
    id: p.id,
    descripcion: p.name,
    fechaComienzoTrabajos: p.workStartDate,
    fechaHistorico: p.historicoDate,
    fechaFinPlanificacion: p.planningEndDate,
    proyectoCerrado: p.projectClosed,
    faseCerrada: p.phaseClosed,
    tieneHijos: p.tieneHijos
  }),
  tap(data=>console.log('Proyecto: ',JSON.stringify(data))),
  catchError(this.handleError)
);

But I need now to get the Hours charged in this project in function of its properties:

  • id
  • fechaComiezoTrabajos
  • fechaFinPlanificacion

That is, I need something like this

连接图

But I get an error cause concatMap returns an Observable<Horas[]> and proyecto$ is an Observable

If I try this

horas$:Observable<Horas[]>
this.horas$=this.proyecto$=this.http.get<ProjectApi>(`${this.urlProyecto}/${this.proyectoId}`)
.pipe(
  map(p => <Proyecto>{
    id: p.id,
    descripcion: p.name,
    fechaComienzoTrabajos: p.workStartDate,
    fechaHistorico: p.historicoDate,
    fechaFinPlanificacion: p.planningEndDate,
    proyectoCerrado: p.projectClosed,
    faseCerrada: p.phaseClosed,
    tieneHijos: p.tieneHijos,
  }),
  tap(data=>console.log('Proyecto: ',JSON.stringify(data))),
  concatMap(proyecto=>this.http.get<Horas[]>(`${this.urlProyecto}/fechainicio/${proyecto.fechaComienzoTrabajos}/fechafin/${proyecto.fechaFinPlanificacion}/horas`)),
  catchError(this.handleError)
);

I get error in both variables

If I try this

this.proyecto$=this.http.get<ProjectApi>(`${this.urlProyecto}/${this.proyectoId}`)
.pipe(
  map(p => <Proyecto>{
    id: p.id,
    descripcion: p.name,
    fechaComienzoTrabajos: p.workStartDate,
    fechaHistorico: p.historicoDate,
    fechaFinPlanificacion: p.planningEndDate,
    proyectoCerrado: p.projectClosed,
    faseCerrada: p.phaseClosed,
    tieneHijos: p.tieneHijos,
  }),
  tap(data=>console.log('Proyecto: ',JSON.stringify(data))),
  catchError(this.handleError)
);

this.horas$=this.proyecto$
  .pipe(
    concatMap(proyecto=>this.http.get<Horas[]>(`${this.urlProyecto}/fechainicio/${proyecto.fechaComienzoTrabajos}/fechafin/${proyecto.fechaFinPlanificacion}/horas`)),
    tap(data=>console.log('Horas: ',JSON.stringify(data)))
  );

I get nothing in his.horas$ in fact the http.get it is not carried out

How can I assign the value returned from concatMap in another observable variable?

Thanks

create another variable like

horas$: Observable<Horas[]>;

this.horas$ = this.proyecto$
    .pipe(
        concatMap(proyecto => ...)
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM