Angular 7-将数据添加到数组而不是替换它

时间:2019-03-17 10:39:42

标签: arrays get angular7

点击按钮后,我正在从wordpress api获取数据

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

这是代码:

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

结果:

enter image description here

我想将所有这些请求数据存储在单个数组中,而不是替换它,并且如果在上一个请求完成后发送由for循环引起的每个请求,那将是很好的选择。

2 个答案:

答案 0 :(得分:1)

只需使用this.commentsResults.push(data);

答案 1 :(得分:0)

也许这会帮助您:

this.commentsResults.merge(data);。 代替此:this.commentsResults = data;