Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
How to consolidate an Observable with informations by a second calls

For educative purpose, I'm trying to call a service that retrieve a list of Posts, and for each post, I would like to make a another call to this service to get the list of comments.

I'm using the data from https://jsonplaceholder.typicode.com/posts

First here are the models I extracted for this service:

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
  comments: PostComment[];
}

export interface PostComment {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}

And here is my current status. My goal is to have an Observable<Post> with the property comments properly filled.

export class PostCommentsCombination implements OnInit {
  constructor(private http: HttpClient) {}

  posts$?: Observable<Post[]>;

  ngOnInit(): void {
    this.posts$ =this.http.get<Post[]> ('https://jsonplaceholder.typicode.com/posts/').pipe(
      switchMap((posts) =>
        posts.map((post) =>
          this.http.get<PostComment[]>(`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`).pipe(
            map((comments) => {
              post.comments = comments;
              return post;
            })
          )
        )
      )
    );
  }
}

But it says it cannot convert Observable<Observable<Post>> into Observable<Post[]>. I cannot blame him, but I'm not sure how to solve this?

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

0

I would try something like this:

ngOnInit(): void {

  const postsUrl = 'https://jsonplaceholder.typicode.com/posts/';

  this.posts$ = this.http.get<Post[]>(postsUrl).pipe(
    map(posts => posts.map(post =>
      this.http.get<PostComment[]>(`${postsUrl}${post.id}/comments`).pipe(
        map(comments => ({...post, comments}))
      )
    )),
    switchMap(postObservables => forkJoin(postObservables))
  );
  
}
over 4 years ago · Santiago Trujillo Denunciar

0

One could forkJoin the requests to the comments, update the post.comments field and return the post back:

this.posts$ = this.http
  .get<Post[]>('https://jsonplaceholder.typicode.com/posts/')
  .pipe(
    switchMap(posts =>
      forkJoin(
        posts.map(post =>
          this.http
            .get<PostComment[]>(`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`)
            .pipe(map(comments => {
              post.comments = comments;
              return post;
            }))
        )
      )
    )
  );

Demo

over 4 years ago · Santiago Trujillo Denunciar

0

posts.map((post) => ...

is basically getting every post and mapping it to an Observable. So you end up with an array of Observables. What you want to do is resolve every Observable in the array to get the output you desire. If you are familiar with promises you want the rxjs equivalent of Promise.all, which is essentially forkJoin - see this post Promise.all behavior with RxJS Observables?

over 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda