我接到了一个服务电话,该电话将十个项目加载到屏幕上。当用户单击“查看更多”按钮时,我将使用不同的分页参数将另一个呼叫发送到该服务。将第二个调用中的新项数组优雅地追加到第一个调用所发出的现有数组中的最佳方法是什么?
下面的示例在技术上是可行的,但是它重置了可观察的原始内容,刷新了屏幕上的所有项目,而不仅仅是添加了新项目。有什么想法吗?受试者可以帮忙吗?
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])
);
答案 0 :(得分:0)
也许尝试类似this之类的东西...
在on-init中进行设置...
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);
}
答案 1 :(得分:-1)
使用您现在拥有的代码,我想您可以将forkJoin更改为此内容
this.items$ = [...this.items$, ...moreItems$];
但是您的itemService
看起来不正确。我想您希望将其设置为类似的内容
this.itemService(this.pageLimit, this.pageOffset).subscribe(res => {
this.items$ = [...this.items$, ...res];
});