0

I am new to Angular and trying to get the values inside postdata, but when i am trying to iterate over it , its only giving me the first value. Attaching my code:

 posts;

 constructor(private getpostservice:GetpostsService) { }

 ngOnInit(): void {
  this.getpostservice.getposts().then(data=>{
  this.posts = [data];

  console.log("Inside home",this.posts);
 })
}

This is my html logic:

<tr *ngFor="let p of posts;index as i">


        <td>
          {{p.postdata[i].title}}
        </td>

      </tr>

This is data format.

Can someone help me to extract title and body please?

4
  • try changing to let p of posts.postdata and then <td> {{p.title}} </td> Commented Jul 30, 2021 at 16:11
  • Why are you storing your data as array this.posts = [data];? If your request response data is an array, you would have an array of arrays - bad idea. And if its just an object, then you would not need a loop to iterate over it. Commented Jul 30, 2021 at 16:14
  • @Fussel sir, can you please give an alternative way to render the data in angular? It would be very much helpful. Commented Jul 30, 2021 at 16:20
  • May be you are looking for nested *NgFor in this case something like here - stackblitz.com/edit/… Commented Jul 30, 2021 at 16:49

1 Answer 1

2

I think what you are trying to achieve based on your console data is:

 constructor(private getpostservice:GetpostsService) { }

 ngOnInit(): void {
  this.getpostservice.getposts().then(data => {
    this.posts = data.postdata;
    console.log("Inside home",this.posts);
 });

and

<ng-container *ngIf="posts">
  <tr *ngFor="let p of posts">
    <td>
      {{p.title}}
    </td>
  </tr>
</ng-container>

Maybe you should also consider using Observables instead of Promises, it's a bit you have to get used to but it is way more powerful and more easy to use.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah some opinion about using Observable instead of Promise, or another alternative is using the async pipe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.