【问题标题】:Angular HttpHeaders responseType: 'text' . giving 'Type 'string' is not assignable to type 'json'"Angular HttpHeaders responseType: 'text' 。给出'类型'字符串'不可分配给类型'json'”
【发布时间】:2019-12-21 09:36:37
【问题描述】:

Angular HttpHeaders responseType: 'text' 。给Type 'string' is not assignable to type 'json'。错误。我知道响应不是 JSON。我不明白如何更改类型?我想获取该文本(HTML)并在之后使用正则表达式对其进行解析。

代码

    const httpOptions = {
      headers: new HttpHeaders({
        accept: '*/*',
        contentType: 'application/x-www-form-urlencoded',
      }),
      responseType: 'text',
    };
    post = this.httpClient.post(destinationUrl, httpBody, httpOptions);

    post.subscribe(
      (res) => {
        console.log(res)
      },
      (error) => {
        console.error('download error:', error)
      },
      () => {
        console.log('Completed')
      },
    );

来自控制台的错误

如您所见,响应类型是文本。由于我不明白的东西,我不能让它接受文本,因为它正在等待 json...

【问题讨论】:

  • 尝试在 httpOptions 中的 responseType: 'text', 之后添加 observe: 'response' ,然后执行 console.log 响应。
  • 您使用的是哪个版本的 Angular?
  • 版本 7.2.0...
  • 至于observe: response,它。在 i 之前出现错误。可以做一个console.log
  • post = this.httpClient.post(destinationUrl, httpBody, httpOptions); post.subscribe( (response) => { console.log(response); return response; }, (err) => { throw err;

标签: angular http-headers angular-httpclient


【解决方案1】:

我解决了这个问题,将 HTTPOptions 作为一个对象

let HTTPOptions:Object = {

        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        }),
        responseType: 'text'
     }
    return this.http.post<any>(url, body,  HTTPOptions ).pipe(
        catchError(this.handleError)
    );

【讨论】:

  • 有什么区别?为什么会这样?
【解决方案2】:

根据official angular documentation

Overload #3 构造一个 POST 请求,将主体解释为 文本字符串并将响应作为字符串值返回。

post(url: string, body: any, options: { headers?: HttpHeaders | { [标题:字符串]:字符串 |细绳[]; };观察?:“身体”;参数?: HttpParams | { [参数:字符串]:字符串 |细绳[]; };报告进度?: 布尔值;响应类型:“文本”; withCredentials?:布尔值; }): 可观察参数 url string 端点 URL。

body any 要替换的内容。

选项对象 HTTP 选项

返回 Observable:响应的 Observable,带有 字符串类型的响应体。

通过查看文档,我们可以做这样的事情。响应(内部)是字符串:

clickMe() {
    this.httpClient.post(
      `https://reqres.in/api/users`,
      {
        name: "paul rudd",
        movies: ["I Love You Man", "Role Models"],
      },
      {
        observe: 'response',
        responseType: 'text',
      }
    ).subscribe(x => console.log('x: ', x.body))
  }

Stackblitz example for code above

【讨论】:

  • 遇到同样的问题。就像订阅函数不关心参数一样,直接失败:(
猜你喜欢
  • 1970-01-01
  • 2020-05-30
  • 2017-12-28
  • 2019-08-18
  • 2021-02-22
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多