如何使用 Angular 发送 HTTP 请求并取回 json 数据 [英] How to send HTTP request and get json data back using Angular

查看:82
本文介绍了如何使用 Angular 发送 HTTP 请求并取回 json 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击获取 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆