[英]Angular method return with http observable
我正在开发一个从 API 检索位置信息的函数。 由于位置数据具有层次结构,我正在尝试实现一个名为 build list 的递归方法,该方法最终会给我一个包含所有子节点的对象。 (我使用的是 Strapi,它只给我一个单一级别的关系信息,我不能限制系统将拥有的级别数)。
buildList(location:string) :Task{
this.task.getLocations(location).subscribe(data=>{
return data;
});
return null;
}
以下是供参考的任务结构,
export interface Task {
task_name: string;
task_description:string;
role_level: number;
location:string;
children:Task[]
id: string;
}
我的问题是,每当我调用 buildList 函数时,它都会返回 null,因为 getLocation 函数基于返回 observable 的 angulars http get 方法。 我期望在内部实现一个递归函数,但它一直给我 null 因为它在 http 请求之前执行 return null。 我也无法删除 return null 因为打字稿给了我错误并非所有代码路径都返回值。 任何使这项工作的建议将不胜感激。
谢谢你
我认为您可以使用全局列表来实现您的目标,然后递归调用 buildList func。
locations:any=[]
buildList(location:string) :void{
this.task.getLocations(location).subscribe(data=>{
this.locations.push(data.location);
buildList(data.location)
});
}
你的方法总是会返回 null 因为你知道 http 客户端是异步的。 因此,如果您想创建一个“递归”函数,一个简单的方法可能是根据需要(无递归方式)使用某些库作为 RxJ 进行嵌套调用,这样可以帮助您等待所有嵌套查询返回结果.
一个伪示例可能是:
import { forkJoin } from 'rxjs';
...
buildList(location:string) :Task{
this.task.getLocations(location).subscribe( mainData => {
const requests = [];
mainData.<list_of_items>.forEach(item => {
requests.push(this.<yourNestedService>.someCall());
});
forkJoin<YourNestedTypeExpected>(requests).subscribe(responses => {
responses.forEach(response {
// Your success responses.
// You can build here the structure that you expect.
})
}), error => {
// There are some error in some query.
console.warn(error);
});
});
}
也许可能比它更复杂,但可能是一个开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.