虚拟角度滚动,不向列表添加数据

时间:2019-02-11 08:57:30

标签: angular typescript angular-material2 infinite-scroll virtualscroll

我尝试使用Hasura的GraphQL后端在Angular 7项目上实现无限虚拟滚动。

我无法弄清楚为什么不添加新数据以及为什么在滚动时会有多个API请求。

以下是组件feed.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { IdeaService } from '@app/core/idea/idea.service';
import { MatDialog } from '@angular/material';
import { IdeaCardComponent } from '@app/shared/idea-card/idea-card.component';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { Observable, BehaviorSubject } from 'rxjs';
import { map, tap, merge, throttleTime, scan, mergeMap } from 'rxjs/operators';

const batchSize = 10;

@Component({
  selector: 'app-idea-feed',
  templateUrl: './idea-feed.component.html',
  styleUrls: ['./idea-feed.component.scss']
})
export class IdeaFeedComponent implements OnInit {
  @ViewChild(CdkVirtualScrollViewport)
  viewport: CdkVirtualScrollViewport;

  isEndOfTheList = false;
  offset = new BehaviorSubject(null);
  infinite: Observable<any[]>;

  length: number;
  ideaList: any[] = [];
  pageIndex = 0;
  pageEvent: any;
  constructor(private ideaService: IdeaService, public dialog: MatDialog) {
    const batchMap = this.offset.pipe(
      throttleTime(500),
      mergeMap(n => this.getIdeasFromServer(n)),
      scan((acc, batch) => {
        return { ...acc, ...batch };
      }, {})
    );

    this.infinite = batchMap.pipe(map(v => Object.values(v)));
    console.log(this.infinite);
  }

  nextBatch(e: any, offset: any) {
    if (this.isEndOfTheList) {
      return;
    }

    const end = this.viewport.getRenderedRange().end;
    const total = this.viewport.getDataLength();

    if (end === total) {
      this.offset.next(offset);
    }
  }

  trackByIndex(i: any) {
    return i;
  }


  ngOnInit() {
    this.ideaService.getTotalIdeaCount().subscribe(data => {
      this.length = data.data.ideas_aggregate.aggregate.count;
    });
  }

  getIdeasFromServer(pageIndex: any) {
    console.log(this.ideaList, this.pageIndex);

    return this.ideaService.getNIdeas(batchSize, pageIndex).pipe(
      map((data: any) => {
        this.pageIndex += 10;
        data.data.ideas.forEach((idea: any) => {
          this.ideaList.push(idea);
        });
        this.ideaList = data.data.ideas;
        return data.data.ideas;
      })
    );
  }
}

这是HTML feed.component.html

<div *ngIf="(infinite | async) as ideaList" class="ideafeed-background">
  <cdk-virtual-scroll-viewport itemSize="100" scrolledIndexChange)="nextBatch($event, pageIndex)">
        <mat-card
          class="idea-card"
          *cdkVirtualFor="let item of ideaList; let i = index; trackBy: trackByIdx">
     {{ item.name }}
    </mat-card>
  </cdk-virtual-scroll-viewport>
</div>

我不确定自己在做什么错。我已遵循this教程

1 个答案:

答案 0 :(得分:0)

我有同样的问题。我更改了push方法:

this.ideaList = [...this.ideaList, idea];