How to handle if API response is a string instead of JSON in Ionic + Angular


If response coming from my API is in JSON format then it works fine but if in non-json format then the function does not work. Here is what I am doing –

In my page.ts

import { ApiconnectService } from '../../apiconnect.service';

export class BinaryGraphPage implements OnInit {
  value : any;
    private cs: ApiconnectService
  ) { }

     this.cs.unilevelGraph().subscribe(response =>{
         this.value = response;


In apiconnect.service.ts

    return this.http.get(this.url+'?sponser='+uid);

The response coming from API is not in JSON format (I tried JSON format and it works fine but for some reason my response need to be in text/string).

In API, response is a long text and contains html tags such as br tag, span and li tag e.g.: Howdy user, this is your graph list 1.item, 2. item, 3.item, etc.

Since response is not in JSON format, so this errors appear in my console. Error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://……

Can you please suggest me how to rewrite the function userGraph() so that it can work with string or text.


Since you are not getting a JSON response, specify the response type in the options. So, the service method becomes:

    return this.http.get((this.url+'?sponser='+uid), { responseType: 'text' });

Answered By – sofa_maniac

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published