简体   繁体   中英

Angular4 - How to detect if a response is JSON or plain text with observable

I'm wondering if there is a way to detect the format of a response in an observable, when using a generic api service to call a variety of endpoints. Some send back JSON, others plain text.

this.http.get(endpoint).map(response => {
    // if JSON
    return response.json();
    // else if plain text
    return response.text();
})...

A ResponseContentType exists in the angular doc but I never found this enum in the response object so I use a "trick" :

this.http.get(endpoint).map(response => {
    const contentType = res.headers.get('Content-type');
   if (contentType == 'application/json') {
    return response.json();   
   } else if (contentType == 'application/text') {
    return response.text();
   }
})...

if someone know where we can find the ResponseContentType enum please told us !

I was never able to find a built in way with Angular to verify JSON, so I just check the content type in the response header.

Here's the function I use:

/**
 * True of the response content type is JSON.
 */
private static isJson(value: Response): boolean {
    return /\bapplication\/json\b/.test(value.headers.get('Content-Type'));
}

Content-Type can have extra stuff in the string so I use a regex to be safe.

I would recommend failing if it's not JSON.

 this.http.get().map((value:Response)=>{
      if(this.isJson(value)) {
         return value;
      }
      throw value;
 });

You can then catch the known JSON responses later in the subscriber. Now you know all responses in the subscriber are getting JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM