I've been using a pattern like the below to chain together http.gets in Angular2 to retrieve information from a hierarchical structure, two layers deep, of folders (all pseudotypescript):
myObservable = this.myService.getSubFolders(topFolderUrl)
.switchMap(subFolders=> this.myService.getInfoFromSubFolders(subFolders))
.map(subFolders=> => {
...do stuff with subFolders...
return subFolders;
}
);
Where myService looks something like this:
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;
}
I then subscribe to myObservable using an | async pipe in my template. Object in myObservable ends up something like:
{
"url": "topFolderUrl",
"otherProps": "otherPropsValue",
"subFolders": [
{
"url": "subFolder1Url",
"otherProps": "otherPropsValue"
},
{
"url": "subFolder2Url",
"otherProps": "otherPropsValue",
}
]
}
However, this relies on this structure of folders being exactly two layers deep - no more, no less I have two related questions:
- How would I refactor this to allow me to recursively work my way down a series of folder n layers deep - I can only request one layer at a time - i.e each subFolder has "subFolders": [] and so on.
- How would I allow the system to cope if there were no subFolders? ie not call getInfoFromSubFolders in the .switchMap
I have a feeling this this is a very common scenario so it is likely to be useful to many people.
Any pointers gratefully received