简体   繁体   中英

Angular method return with http observable

I am working on a function to retrieve location information from an API. As the location data have a hierarchical structure I am trying to implement a recursive method called build list which will eventually give me an object with all the child nodes included inside. ( I am using strapi and it only gives me a single level relational information and I cannot limit the no of levels the system will have).

  buildList(location:string) :Task{
    this.task.getLocations(location).subscribe(data=>{
      return data;
    });
    return null;
  }

Following is the task structure for reference,

export interface Task {
    task_name: string;
    task_description:string;
    role_level: number;
    location:string;
    children:Task[]
    id: string;
  }

My issue is that whenever I call the buildList function, it will return null as the getLocation function is based off of angulars http get method which returns an observable. I am expecting to implement a recursive function inside but it keeps giving me null as it executes return null before the http request. I also cannot remove the return null as typescript gives me the error not all code paths return a value . Any suggestions to make this work will be really appreciated.

Thank You

I think you can use a global list to achieve your goal and then recursively call buildList func.

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

Your method always will return null because as you know http client is asynchronous. So, if you want to make a "recursive" function a simple aproach could be to have nested calls as you need (no recursive way) using some library as RxJs than can help to you to wait to have all nested queries to return the result.

A pseudo example could be:

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

Maybe can be more complex that it but could be a beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM