【发布时间】:2018-01-08 04:55:40
【问题描述】:
我一直在使用类似下面的模式将 Angular2 中的 http.gets 链接在一起,以从文件夹的分层结构(两层深)中检索信息(所有伪脚本):
myObservable = this.myService.getSubFolders(topFolderUrl)
.switchMap(subFolders=> this.myService.getInfoFromSubFolders(subFolders))
.map(subFolders=> => {
...do stuff with subFolders...
return subFolders;
}
);
myService 看起来像这样:
getSubFolders(topFolderUrl): Observable<Folder[]> {
return this.http.get(topFolderUrl)
.map(res => {
let body = res.json();
let foldersToReturn: Folder[] = [];
for (let subfolder of body.subFolders) {
let tempFolder = new Folder;
tempFolder.url = subfolder.url;
tempFolder.otherProps = subfolder.otherPropValue;
}
return foldersToReturn;
}
.catch(this.handleError);
}
getInfoFromSubFolders(subFolders:Folder[]): Observable<Folder[]> {
let calls: any[] = [];
for (let folder of subFolders:Folder){
calls.push(
this.http.get(folder.url)
);
var subject = new Subject<Folder[]>(); //see: http://stackoverflow.com/a/38668416/2235210 for why Subject
Observable.forkJoin(calls).subscribe((res: any) => {
let foundFolder = subFolders.find(folder=> {
return response.url.indexOf(folder.url)!==-1;
});
for (let response of res){
let bodyAsJson = JSON.parse(response._body);
foundFolder.otherProps = bodyAsJson.otherPropValue;
}
subject.next(subFolders);
});
return subject;
}
然后我使用 | 订阅 myObservable我的模板中的异步管道。 myObservable 中的对象最终类似于:
{
"url": "topFolderUrl",
"otherProps": "otherPropsValue",
"subFolders": [
{
"url": "subFolder1Url",
"otherProps": "otherPropsValue"
},
{
"url": "subFolder2Url",
"otherProps": "otherPropsValue",
}
]
}
但是,这依赖于这种文件夹结构恰好是两层深 - 不多也不少,我有两个相关的问题:
- 我将如何重构它以允许我以递归方式向下处理一系列文件夹 n 层 - 我一次只能请求一个层 - 即每个子文件夹都有“子文件夹”: [] 等等。
- 如果没有子文件夹,我将如何让系统应对?即不在 .switchMap 中调用 getInfoFromSubFolders
我感觉这是一个非常常见的场景,因此它可能对很多人有用。
感谢您的指点
【问题讨论】:
标签: angular rxjs observable