Home > Back-end >  Use the same component to show different data on the same page depending on http response in Angular
Use the same component to show different data on the same page depending on http response in Angular

Time:04-25

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
    });
  }
}

CodePudding user response:

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...}

CodePudding user response:

Depending on what the response is that you get from the server it should be as easy as

 preparePostData() {
    this.postService.getPostById(this.postId).subscribe((res) => {
      // assign the res data to the postData variabale
      this.postData = res;
    });
  }

The response you get from the server would be helpful and maybe the method that actually sends the GET request.

  • Related