-1

I am calling a API service and assigning API response to any[] type.

Problem is method was execution was completed without waiting API response completes?

Below is my code

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!
Shakeer Hussain
  • 2,230
  • 7
  • 29
  • 52
  • Please do some research on async generally and JS promises (or observables) specifically. There are so many questions, tutorials, articles and blog posts addressing this already. – jonrsharpe Feb 26 '19 at 21:02
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – Heretic Monkey Feb 26 '19 at 21:03

1 Answers1

3

There are two issues in your code.

1- Your method is returning an array and you subscribed to it (although has async issue)

2- Method is returning array at the end and it happens before your promise result become ready

Solution 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!");
})); 

Solution 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!");
})); 

Note

In both solutions you don't need public responseData:any=[]; in your service

Reza
  • 18,865
  • 13
  • 88
  • 163