【问题标题】:Angular4 http get parse errorAngular4 http获取解析错误
【发布时间】:2018-02-11 23:44:02
【问题描述】:

请求mydomain/request返回像"accepted""declined"这样的json字符串

我会在 Angular 中使用 request 来获取这个字符串:

  getStatus(jobOfferId): Promise<string> {
    const url = "someurl";

    return this.httpClientService.get(url)
      .toPromise()
      .then(response => response as string);
  }

这可以在 angular 2 中工作,但我刚刚升级到 angular 4,这个请求会返回错误

"Http failure during parsing for https://mydomain/request"

【问题讨论】:

  • 您能否提供一份回复样本?
  • @ochi 我做了,它只是一个用括号括起来的字符串"
  • @LazarLjubenović 在我的代码中没有提到我专门使用 HttpClient 类。 httpClientService 是一个处理与 http 相关的东西的抽象注入。类本身已迁移。
  • @LazarLjubenović 目前 httpClientService.get 与 HttpClient.get 相同,但在迁移之前它有不同的实现
  • @Benedictus 你在寻找类似this的东西吗

标签: javascript json angular http typescript


【解决方案1】:

JSON 是默认的预期响应类型。您可以尝试强制使用“文本”并打印结果以了解发生了什么:

httpClient.get('http://some.com/endpoint/', { responseType: 'text' }).subscribe(result => {
    console.log(result);
});

【讨论】:

  • error TS2345: Argument of type '{ responseType: "text"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'responseType' are incompatible. Type '"text"' is not assignable to type '"json"'. 另外,headers 没有定义。
  • @PhilippLudwig 我从示例中删除了可选标头,但是 responseType: ''text' 是正确的。您可以查看类似的示例here。这个答案也适用于 Angular 4,Angular 5 有 a new http service
  • 如果您的响应类型是纯文本而不是 JSON,请确认这是正确的方法。您在上面的评论中提到您的 httpClientService 是 Angular 的 httpClient 的抽象层。如果这不起作用,则问题可能在于您如何实现抽象。
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
相关资源
最近更新 更多