【问题标题】:Angular method return with http observableAngular 方法返回带有 http observable
【发布时间】:2021-09-26 10:13:47
【问题描述】:

我正在开发一个从 API 检索位置信息的函数。由于位置数据具有层次结构,因此我正在尝试实现一种称为构建列表的递归方法,该方法最终将为我提供一个包含所有子节点的对象。 (我使用的是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 。我也无法删除返回 null,因为 typescript 给了我错误并非所有代码路径都返回值。任何使这项工作的建议将不胜感激。

谢谢

【问题讨论】:

    标签: angular typescript http asynchronous observable


    【解决方案1】:

    您的方法总是会返回 null,因为您知道 http 客户端是异步的。所以,如果你想创建一个“递归”函数,一个简单的方法可能是使用一些库作为 RxJs,根据需要(没有递归方式)进行嵌套调用,而不是帮助你等待所有嵌套查询返回结果.

    一个伪例子可能是:

     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);
             });
          
        });
      }
    
    

    也许比它更复杂,但可能是一个开始。

    【讨论】:

      【解决方案2】:

      我认为您可以使用全局列表来实现您的目标,然后递归调用 buildList func。

        locations:any=[]
        buildList(location:string) :void{
          this.task.getLocations(location).subscribe(data=>{
            this.locations.push(data.location);
            buildList(data.location)
          });
        }
      

      【讨论】:

        猜你喜欢
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-18
        • 1970-01-01
        相关资源
        最近更新 更多