如何使用 Angular 发送 HTTP 请求并取回 json 数据 [英] How to send HTTP request and get json data back using Angular
问题描述
当用户单击获取 HTTP 数据"按钮时,app.component
中定义的 getData()
方法调用 http
服务的 getData()
方法应该返回 json
数据.但它返回的是 ZoneAwarePromise
对象:
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);
}
这是 Stackblitz 项目的链接:
Here is the link to the Stackblitz project:
https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts
如何解决这个问题,让http服务返回json数据?
How to fix this issue and make the http service to return the json data?
推荐答案
我在 stackblitz 链接中修复了这个问题.- https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts
I have the fixed the issue in the stackblitz link. - https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts
问题是,在服务中,您没有在创建过程中订阅 observables 或使用 then 或 cathErrors 收听承诺(这是您的情况)
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.
这篇关于如何使用 Angular 发送 HTTP 请求并取回 json 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!