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

时间:2019-02-26 21:00:31

标签: angular typescript angular-promise

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

问题是方法是否在没有等待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 个答案:

答案 0 :(得分:0)

您的代码中有两个问题。

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=[];服务