【问题标题】:How to send HTTP request and get json data back using Angular如何使用 Angular 发送 HTTP 请求并取回 json 数据
【发布时间】:2020-06-10 11:42:38
【问题描述】:

当用户单击“获取 HTTP 数据”按钮时,app.component 中定义的getData() 方法调用http 服务的getData() 方法,该方法应该返回json 数据。但相反,它返回 ZoneAwarePromise 对象:

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 项目的链接:

https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts

如何解决这个问题,让http服务返回json数据?

【问题讨论】:

    标签: angular typescript promise request observable


    【解决方案1】:

    我已经修复了 stackblitz 链接中的问题。 - https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts

    问题是,在服务中,您没有订阅 observables 或在创建期间使用 then 或 cathErrors 收听承诺(这是您的情况)

    相反,您应该订阅要注入它的组件中的服务。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多