我正在调用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!
答案 0 :(得分:0)
您的代码中有两个问题。
1-您的方法正在返回一个数组,并且您已订阅它(尽管存在异步问题)
2-方法最后返回数组,它发生在诺言结果准备就绪之前
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!");
}));
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=[];
服务