Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!