IWI
IWI

Reputation: 1608

Angular HttpHeaders responseType: 'text' . giving 'Type 'string' is not assignable to type 'json'"

Angular HttpHeaders responseType: 'text' . giving Type 'string' is not assignable to type 'json'. error. I know the response is not JSON. I do not understand how to change the type? I want to take that text (HTML) and parse it with a regex after.

Code

    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')
      },
    );

Error from console enter image description here

As you can see, the response type is text. Because of something I don't understand, I cannot make it accept text, as it is waiting for json...

Upvotes: 4

Views: 12858

Answers (2)

NITIN VERMA
NITIN VERMA

Reputation: 236

I solved this issue making HTTPOptions as an Object

let HTTPOptions:Object = {

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

Upvotes: 22

alt255
alt255

Reputation: 3566

According to official angular documentation

Overload #3 Constructs a POST request that interprets the body as a text string and returns the response as a string value.

post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable Parameters url string The endpoint URL.

body any The content to replace with.

options object HTTP options

Returns Observable: An Observable of the response, with a response body of type string.

By looking at documentation, we can do something like this. The response (inside body) is string:

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

Upvotes: 1

Related Questions