【发布时间】:2019-12-13 15:52:13
【问题描述】:
我在 Angular 6 中使用异步管道显示 youtube 视频。它在第一次加载时工作正常。
这就是我的使用方式。
组件 HTML 文件:
<div id="youtube" class="search-results" *ngIf="(trendingVideos | async) as videos; else loadingOrError"></div>
组件TS文件:
public trendingVideos: Observable<VideoClass[]>;
private loadVideos(videosPerPage?: number, regionCode?: string, videoCategoryId?: number) {
this.trendingVideos = this.youtubeService.getTrendingVideos(videosPerPage, regionCode, videoCategoryId, false)
.pipe(
catchError((error: any) => {
this.loadingError$.next(true);
return throwError(error);
})
);
}
捕捉错误也可以正常工作。
服务文件:
public getTrendingVideos(videosPerPage?: number, regionCode?: string, videoCategoryId?: number, paginationMode?: boolean): Observable<VideoClass[]> {
const params: any = {
part: appConfig.partsToLoad,
chart: appConfig.chart,
videoCategoryId: videoCategoryId ? videoCategoryId : appConfig.defaultCategoryId,
regionCode: regionCode ? regionCode : appConfig.defaultRegion,
maxResults: videosPerPage ? videosPerPage : appConfig.maxVideosToLoad,
key: appConfig.youtubeApiKey
};
return this.http.get<any>(appConfig.getYoutubeEndPoint('videos'), { params })
.pipe(
map(
(data) => {
return data.items
.map((item) => new VideoClass(item))
.filter((item) => item.id !== '');
}
),
catchError(this.handleError('getTrendingVideos'))
) as Observable<VideoClass[]>;
}
当我第一次加载数据时它工作正常。现在我正在开发无限滚动。所以我再次调用这个 API。但想将数据合并到以前加载的数据中。
当我的无限滚动插件调用它时,它每次都会用新数据替换数据。
这是无限滚动功能:
private onScroll(){
let videosData:Observable<VideoClass[]> = this.youtubeService.getTrendingVideos(this.videoCount, this.regionCode, this.categoryID, true)
.pipe(
catchError((error: any) => {
this.loadingError$.next(true);
return throwError(error);
})
);
// Here how i merge this same video data to previously loaded trending videos data.
}
有什么帮助吗?
【问题讨论】:
-
尝试创建一个 VideoClass 的
array并将 api 的结果附加到该数组中。使用相同的array以html显示数据。 -
我将如何使用异步管道。 @SarthakAggarwal
-
您可以只使用
*ngIf来检查array的长度是否为0。如果是0,则表示尚未从 api 检索数据。如果length > 0,您可以显示数据并在进一步滚动时,您可以调用您的api并将数据附加到同一个数组中。 -
使用异步管道的任何方式。 @SarthakAggarwal
-
在rxjs中,如果要添加到之前返回的结果中,要使用scan或者mergeScan操作符
标签: javascript angular rxjs