Search code examples
javascriptarraysgetangular7

Angular 7 - adding data to an array instead of replacing it


I'm getting data from wordpress api after button click:

<a (click)="initGetComments()">Get comments</a>

this is the code:

export class AppComponent {

  commentsResults: CommentsItem[] = [];

  getComments(ID:string): Observable<CommentsItem[]> {
    console.log(ID);

    return this.http
      .get(`https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/posts/${ID}/replies/?number=1`)
      .map(res =>
        res.comments.map(
          item =>
            new CommentsItem(
              item.post.ID,
              item.ID,
              item.author.name,
              item.author.avatar_URL,
              item.date,
              item.raw_content
            )
        )
      );
  }

  initGetComments(){
    var posts = document.getElementsByClassName('single-post');

    var i=0;
    for( i; i < posts.length; i++ ) {
      this.getComments(posts[i].id).subscribe(data => {
        this.commentsResults = data;
        console.warn("commentsResults =", this.commentsResults);
      })
    }

  }
}

export class CommentsItem {
  constructor(
    public post_ID: number,
    public ID: number,
    public author: string,
    public avatar: string,
    public date: string,
    public content: string
  ) {}
}

And result:

enter image description here

I would like store all of this requests data into a single array instead of replacing it and would be great if each of request induced by a for loop be send when the previous one has finished.


Solution

  • Simply use this.commentsResults.push(data);