-3

Clicking the Click Me button calls the getDataAsObservable method defined in http.service.ts script:

export class HttpService {
  jsonFile = '../assets/products.json';

  constructor(private http: HttpClient) {}

  getDataAsObservable(): Observable<any> {
    return this.http.get(this.jsonFile)
  }
} 

After receiving the observable from the http service the requestDataAndWait method defined in the app.component.ts script assigns the received response to the local variable data and returns it back to the onClick method. But instead of receiving the array data the onClick method gets ZoneAwarePromise object:

enter image description here

  async requestDataAndWait() {    
    let data = [];
    await this.http.getDataAsObservable()
      .toPromise().then(response => {data=response;} );
    return data
  }

Here is the link to the Stackblitz project: https://stackblitz.com/edit/angular-ivy-bygaut?file=src%2Fapp%2Fapp.component.ts

How to make the requestDataAndWait return the data array instead of the ZoneAwarePromise object?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • 2
    Please see the canonical https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call. `async` functions **always** return a promise (that's the whole *point* of them) and you can't get around asynchronous control flow by assuming it doesn't exist. It seems like you've been told this twice already: https://stackoverflow.com/q/62295405/3001761, https://stackoverflow.com/q/62296092/3001761. – jonrsharpe Jun 10 '20 at 17:29

1 Answers1

1

You need to first change the Service class to return a response like this

getDataAsObservable(): Promise<any> {
 return this.http.get(this.jsonFile).toPromise()
}

Then change your component class like this

async onClick() {
 let result = await this.requestDataAndWait();
 console.log("result:", result);
}

async requestDataAndWait() {  
 return await this.http.getDataAsObservable();
}
Lasal Sethiya
  • 201
  • 1
  • 4
  • 17
  • https://stackoverflow.com/questions/62296092/how-to-make-synchronous-http-request-in-angular-8-or-9-make-a-request-and-wait#comment110200905_62296464 (in this case it's `val` that's the pointless assignment). Also `getDataAsObservable` isn't a great name for a function that returns a promise... – jonrsharpe Jun 10 '20 at 17:43
  • Yes correct. But I wanted him to understand quickly. instead of refactoring. I will adjust a bit. Thanks a lot for the comment! – Lasal Sethiya Jun 10 '20 at 17:45