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

122
Vistas
Use the same component to show different data on the same page depending on http response in Angular

I have a post component and I want to display many posts on the same page by getting the post data by its id from the server-side, but all posts display the same data of one post. How to display the data of each post??

<app-post *ngFor="let post of posts" [postId]="post"></app-post>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  constructor(
  ) {}

  posts = [
    '62653bd48622e648819139e2',
    '626565e78622e64881913bda',
    '6264878bdb7ea6a449ca9698',
    '62658e988622e648819140e0',
    '62658f218622e64881914118',
    '6265903c8622e6488191416d',
  ];

  ngOnInit(): void {}
}
@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.scss'],
})
export class PostComponent implements OnInit {
  @Input() postId!: string;

  postData: PostData = this.postService.initialPostData;
  postDataAssigned = false;

  constructor(
    private postService: PostService,
    private userInfoService: UserInfoService
  ) {}

  ngOnInit() {
    this.preparePostData();
  }

  preparePostData() {
    this.postService.getPostById(this.postId).subscribe((res) => {
      // assign the res data to the postData variabale
    });
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're assigning your data to a property of a shared service, so all components are sharing the same variable. Objects are assigned by reference, so you are not creating a separate copy in each component.

With this line:

postData: PostData = this.postService.initialPostData;

You've just created an alias for initialPostData rather than a new object.

You can either clone the initial data like so:

postData: PostData = JSON.parse(JSON.stringify(this.postService.initialPostData;))

Or for better performance just copy initialPostData from your service and paste in the component instead:

postData: PostData = {prop1: 1, prop2: 'foo', etc...}
about 4 years ago · Juan Pablo Isaza 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