Search code examples
angularhttpclient

How to subscribe plain/text response in angular


My post API is returning plain lorem ipsum text, but the payload is in JSON format. my problem is I am not getting the response in the main block of a subscriber, but able to view the response in the error block. Pls, help me to get a fix.

here is my code snippet.

const path = 'sample URL';
const body = { 
   id: 'xyz',
   name: 'abc'
};
const httpOptions = {
   headers: new HttpHeaders(
        {
          'Accept': 'text/plain',
          'Content-Type': 'application/json',
          'responseType': 'text'

        })};
this.http.post(path, body, httpOptions).subscribe(
  (res)=>{ },
  err=>{ 
    console.log("===",err);
  }
);

I also tried res.text() but not worked.


Solution

  • There is mistake in your code. Response Type is not part of headers. Its another option like header. See code below that will work for you.

    const path = 'sample URL';
    const body = {
      id: 'xyz',
      name: 'abc'
    };
    let headers = new HttpHeaders({
        'Accept': 'text/plain',
        'Content-Type': 'application/json',
      })
    this.http.post(path, body, {headers, responseType: 'text'}).subscribe((res) => {