When a user clicks "Get HTTP Data" button the getData()
method defined in the app.component
calls http
service's getData()
method that is supposed to return the json
data. But instead it returns the ZoneAwarePromise
object:
export class HttpService {
jsonFile = '../assets/products.json';
getData(): Promise<any> {
return this.http.get(this.jsonFile)
.toPromise()
.then(response => {
console.log(">>> .then got response:", response);
})
.catch(this.handleError);
}
Here is the link to the Stackblitz project:
https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts
How to fix this issue and make the http service to return the json data?
I have the fixed the issue in the stackblitz link. - https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts
The problem is, in the service, you do not subscribe to observables or listen to the promises using then or cathErrors during the creation( this is your case )
Rather, you should subscribe to the service in the component, where you are injecting it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.