[英]How to send HTTP request and get json data back using Angular
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.当用户单击“获取 HTTP 数据”按钮时, app.component
中定义的getData()
方法会调用http
服务的getData()
方法,该方法应该返回json
数据。 But instead it returns the ZoneAwarePromise
object:但它返回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:这是 Stackblitz 项目的链接:
https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts 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?如何解决此问题并使 http 服务返回 json 数据?
I have the fixed the issue in the stackblitz link.我已经在 stackblitz 链接中解决了这个问题。 - https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts - 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 )问题是,在服务中,您不订阅可观察对象或在创建期间使用 then 或 cathErrors 听取承诺(这是您的情况)
Rather, you should subscribe to the service in the component, where you are injecting it.相反,您应该订阅组件中的服务,您将在其中注入它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.