我有一个 REST API 接口(interface),它只能让我获得一些信息的第一级。
例如我想收集组。每个组都可以有子组。因此,例如“组 1”具有子组“组 A”和“组 B”。 “A 组”有子组“GroupX”。等等。
但是 API 只为我提供了组名的第一级组。所以我将“Group 1”传递给 API,它返回“Group A”和“Group B”。要获取 A 组的 supgroups,我需要再次调用 API。但我不知道它会有多少次迭代。
所以我考虑过使用递归,但我没有走得太远。
到目前为止我的代码:
getGroupChildren(group:string){ return this restService.getGroupChildren(group)}
getGroups():Promise{
let collection:string[] = [];
return this.getGroupChildren("Group A").then((result)=> {
if(result.data.length !==0){
return this.getGroupChildren(data[0].groupName);
}
});
}
现在这只会返回第一个元素的第一个 Supgroups。
我怎样才能做到无论有多少,总能找到每个 Supgroup?也许使用 Observables 好?
这里是一个 API 调用的示例结构:
{ "groupName" : "Group_1", "children" : ["Group_A", "Group_B"]}
您可以通过 flatMap
实现您想要的效果Observable
的运营商
getGroups(group: string) {
return this.http.get(`/group/{group}`).flatMap(response => {
if (response.children.length === 0) { // you hit a leaf, stop recursion here
return Observable.of(response);
} else { // there are more levels to go deeper
return this.getGroups(response.children[0].groupName);
}
});
}
biên tập使用 Promise
假设您使用 GroupService
它返回数据而不是 HttpClient
.您可以转换 Hứa
đếnObservable
Và fromPromise
运营商。
getGroups(group: string) {
return Observable.fromPromise(this.groupService.get(group)).flatMap(response => {
if (response.children.length === 0) { // you hit a leaf, stop recursion here
return Observable.of(response);
} else { // there are more levels to go deeper
return this.getGroups(response.children[0].groupName);
}
});
}
Chỉnh sửa 2 使用此服务
让我们看一下您的示例。你有以下 json
{
"groupName": "Group_1",
"children" : ["Group_A", "Group_B"]
}
在您的组件文件中,您按如下方式调用该服务
...
this.recursiveGroupService.getGroups("Group_1")
.subscribe(response => {
// at this point response will be `Group_A`
})
编辑3获取整个对象
这次我们将使用 forkJoin
并调用getGroups
对于所有的 child ,并在 children
中收集结果数组。
Để ý:我自己还没有测试过这段代码。它可能包含一些错误。如果有,请告诉我。
import { forkJoin, of } from 'rxjs';
import { map } from 'rxjs/operators';
getGroups(group: string) {
let retVal;
return Observable.fromPromise(this.groupService.get(group)).flatMap(response => {
retVal = {
groupName: response.groupName
};
if (response.children.length === 0) { // you hit a leaf, stop recursion here
return of(retVal);
} else { // there are more levels to go deeper
// this will create list of observable for each child
const children$ = response.children.map(
child => this.getGroups(child));
// forkJoin will execute these observables in parallel
return forkJoin(children$).pipe(
map(results => {
// results is an array containing children data
retVal.children = results;
return retVal;
})
);
}
});
}
Tôi là một lập trình viên xuất sắc, rất giỏi!