【发布时间】:2019-10-27 02:10:41
【问题描述】:
我有“mainData”服务,它由三部分组成:
-
currentPage被分页器组件用来切换页面。可以随时更新。 -
folders包含当前文件夹中的所有文件夹。有 2 个组件使用此 observable(文件夹内容列表的类型) -
files包含当前文件夹中的所有文件。有 3 个组件使用此 observable(文件夹内容列表的类型)
默认视图是没有文件夹的视图,因此我不想进行不必要的 HTTP 调用。
public currentPage = new ReplaySubject(1);
public folders: Observable<FLFolder[]>;
public files: Observable<FLFile[]>;
constructor(
activatedRoute: ActivatedRoute,
folderService: FolderService,
fileService: FileService,
) {
// Populate `this.currentPage`
activatedRoute.queryParams.pipe(
take(1),
// Wait until end of this sync tick. If no emission is made, it will use default in the next tick.
takeUntil(timer(1, queueScheduler)),
defaultIfEmpty<Params>({}),
).subscribe(query => {
if (query.page) {
this.currentPage = +query.page;
} else {
this.currentPage = 1;
}
});
/** This observable is internal, only to be used by `folders` and `files` */
const folderIDAndPage: Observable<[string, number]> = combineLatest(
activatedRoute.url.pipe(
switchMap(segments => folderService.getFoldersFromSegments(segments)),
distinctUntilChanged(),
),
this.currentPage.pipe(
distinctUntilChanged(),
),
).pipe(
// Prevent repeating HTTP somehow...
publishReplay(1),
refCount(),
);
this.folders = folderIDAndPage.pipe(
switchMap(([folderID, page]) => folderService.getFfolders(folderID, page)),
// Prevent repeating HTTP somehow...
publishReplay(1),
refCount(),
);
this.files = folderIDAndPage.pipe(
switchMap(([folderID, page]) => fileService.getFiles(folderID, page)),
// Prevent repeating HTTP somehow...
publishReplay(1),
refCount(),
);
}
当没有订阅 folders 或 files 时,不会生成 HTTP。但即使一个人只订阅其中一个,folders 和 files 也会被填充(在进行 HTTP 调用时)并同时更新。
【问题讨论】:
标签: angular typescript rxjs rxjs6