加载更多按钮在Angular中创建新的html标签

时间:2017-12-19 09:32:25

标签: angular

我发现这个例子是为了在Angular中添加基于* ngfor语句的新标签,但我的问题是每当我向API发送请求并返回新数据时它会替换旧数据,每个请求都包含新的10个文本,而我尝试加载旧10下面的其他新10,如下例所示: https://plnkr.co/edit/rkTlnnClu7tjHC19UC41?p=preview

main.component.ts:

public incCount(loadMore) {
        this.pageNumber = this._newsFeedService.loadMore += 1;
        return this.pageNumber * 10;
    }

    newsFeed() {
        this.user.page = this.incCount(this._newsFeedService.loadMore);
        this._newsFeedService.newsFeedService(this.user)
            .subscribe(
                response => {
                    this.result = response;
                    if (this.result.code == -501) {
                        // this.router.navigate(['/verify'])
                    } else if (this.result.code == 1) {
                        this.data = [];
                        this.result.data.posts.forEach(item => {
                            this.data.push(item);
                        });
                        console.log(this.data);
                    }
                    else {
                        this.alert = this._appService.newAlert('danger', this.result.msg);
                    }
                },
                error => console.log(error)
            );
        console.log(this.user.page);
    }

main.component.html:

 <div *ngFor="let item of data">
        <article class="hentry post">
            <mat-card>
                <mat-card-header>
...
...
...
  <p>{{item.postText}}</p>
...
...
...
              </mat-card-actions>
            </mat-card>
        </article>
    </div>
<button class="form-control" (click)="newsFeed()" >Load More</button>

当我按newsFeed()按钮时,旧文本被新文本替换,如何在旧文本下面生成新的10 {1}}新文本?

1 个答案:

答案 0 :(得分:-1)

您在代码中明确说明要重置HTTP调用成功的数据:

else if (this.result.code == 1) {
     this.data = []; <- here

如果您想为数据添加更多项目,可以通过

更改此声明
    else if (this.result.code == 1) {
             this.data = this.data || []; // <- will assign new array on the first call, and do nothing if data is already initialized 
             ...