【问题标题】:Angular HttpClient response is null but network tools show responseAngular HttpClient 响应为空,但网络工具显示响应
【发布时间】:2019-09-25 19:07:14
【问题描述】:

在我从 4.x 更新到 5 的 Angular 应用程序上工作,并且我有一个调用服务器的服务,但是当开发工具中的网络窗格显示预期响应时,响应为 null。

服务方法如下:

public ExportPendingInvoicesReport(data: InvoicePaginationRequest){
    const link = AppSettings.API_REPORTS_EXPORT_PENDING_INVOICES_REPORT;
    const params = this.mapRequestParameters(data);

    console.log(params.keys());

    this.httpClient.get<string>(link, {params}).subscribe((response: any) => {
        DownloadHelper.DownloadFile('PendingInvoices.csv', 'CSV', response._body);
    })
}

mapRequestParameters 返回一个有效的HttpParams 对象,网络开发工具将其显示为响应:

但在控制台中,我得到了 response 对象的空值。为什么会这样?

使用当前代码更新。

【问题讨论】:

  • 您的响应不包含 JSON,因此响应不可能是具有 _body 属性的对象。请参阅 angular.io/api/common/http/HttpClient#get 的重载 #3,了解如何以文本形式获取响应正文。
  • 这是有道理的,但即使没有response._bodyresponse 仍然为空。现在看文档。 (即使使用.get&lt;string&gt;() .....

标签: angular angular-httpclient


【解决方案1】:

使用参数选项{ responseType: 'text' }调用。

this.httpClient.get(link, {params: params, responseType: 'text'})

这种方式响应正文不会被视为 json。

【讨论】:

  • 感谢您非常明确的答复。现在测试一下。
  • @ChrisRutherford - 我有错误的重载,因为你已经在传递选项。添加responseType。查看更新的答案。
  • 仍然收到错误,指出该类型 '"text"' is not assignable to type '"json"'
  • @ChrisRutherford - 请参阅我在上面的答案中的代码,不要调用get 的通用版本(所以没有类型转换)。您在subscribe 回调中得到的响应是一个原始字符串。
  • 我认为可以做到!
猜你喜欢
  • 1970-01-01
  • 2022-12-05
  • 2019-06-20
  • 1970-01-01
  • 2015-12-27
  • 2019-01-12
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多