Angular HttpHeaders responseType: 'text' 。给出“类型‘字符串’不可分配给类型‘json’”

IWI*_*IWI 1 http-headers angular angular-httpclient

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')
      },
    );
Run Code Online (Sandbox Code Playgroud)

来自控制台的错误 在此处输入图片说明

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

小智 12

我解决了这个问题,使 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)
    );
Run Code Online (Sandbox Code Playgroud)