如何将 Observable 数组附加到通过 Angular 异步管道消耗的现有数组?

How to append an Observable array to existing one consumed via Angular async pipes?

我接到一个服务电话,将十个项目加载到屏幕上。当用户单击 "View More" 按钮时,我会使用不同的分页参数向该服务发送另一个调用。将第二次调用中的新项目数组优雅地附加到第一次调用发出的现有数组中的最佳方法是什么?

我下面的示例在技术上是可行的,但它重置了原始的可观察对象,刷新了屏幕上的所有项目,而不是仅仅添加了新的项目。想法? Subjects 可以帮忙吗?

private onViewMoreClicked(): void {
    this.pageOffset += this.pageLimit;

    const moreItems$ = this.itemService.get(
        this.pageLimit,
        this.pageOffset
    );

    this.items$ = forkJoin(this.items$, moreItems$).pipe(
        map(([a, b]) => [...a, ...b])
    );

使用您现在拥有的代码,我认为您可以将 forkJoin 更改为这个

this.items$ = [...this.items$, ...moreItems$];

但是你的 itemService 看起来不对劲。我想你希望它像这样设置

this.itemService(this.pageLimit, this.pageOffset).subscribe(res => {
    this.items$ = [...this.items$, ...res];
});

也许可以试试 或这个...

初始化时的设置…

ngOnInit() {
   this.pageOffset = 0;

    this.items$ = this.nextPage$.pipe(
        // load first batch when Angular async pipe subscribes
        startWith(this.pageOffset),
        // switch observable to output of getMessages
        switchMap(offset => this.itemService.get(
            this.pageLimit,
            offset
        )),
        // add newly-emitted batch to previously-emitted items
        scan((acc, curr) => {
            acc.push(...curr);
            return acc;
        }, [])
    );
}

这应该是视图更多的点击处理程序…

private onViewMoreClicked(): void {
   this.pageOffset += this.pageLimit;

   // load new items into message$  
    this.nextPage$.next(this.pageOffset);
}