如何等待 return 方法直到服务响应在 Angular 完成?

How to wait a return method until service response completes in Angular?

我正在调用 API 服务并将 API 响应分配给任何[] 类型。

问题是方法的执行没有等待 API 响应完成?

下面是我的代码

Component.ts

  this.catalogService.getCatalogsData().subscribe((data => {
     this._catalogData=data;
      console.log("catalogService function execution done!");
   })); 

service.ts

public responseData:any=[];

 constructor(private http: HttpClient) { 
      }
    public getCatalogsData(){

      debugger;

           this.http.get(this.APIUrl}}).toPromise().then(  
                data => {  
                      this.responseData = data as string [];  
                      console.log("API Response completed");
                  }  
              ); 

       return this.responseData;
      }

Logs Output: -
catalogService function execution done!
API Response completed

Expected OutPut:-
API Response completed
catalogService function execution done!

您的代码中有两个问题。

1- 你的方法返回一个数组,你订阅了它(尽管有异步问题)

2- 方法在末尾返回数组,它发生在您的承诺结果准备就绪之前

解决方案 1:

public getCatalogsData(): Promise<any>{

       return this.http.get(this.APIUrl).toPromise();
}

this.catalogService.getCatalogsData().then((data => {
     this._catalogData=data;
      console.log("catalogService function execution done!");
})); 

解决方案 2

public getCatalogsData(): Observable<any>{
          return this.http.get(this.APIUrl);
}

this.catalogService.getCatalogsData().subscribe((data => {
     this._catalogData=data;
      console.log("catalogService function execution done!");
})); 

备注

在这两种解决方案中,您的服务中都不需要public responseData:any=[];