1

I am doing http client request

export class MapjsonService{
  theUrl = 'http://localhost:4200/api/Lat_Long.json';
  constructor(private http: HttpClient) { }

  fetchNews(): Observable<any>{
    return this.http.get(this.theUrl)
  }

It is working about 99.99% of the time sadly this is running so often that is fails like once every 10 mins with

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/api/Lat_Long.json", ok: false, …}

and

"Http failure during parsing for http://localhost:4200/api/Lat_Long.json"

Now I figured out for some reason my nrql query from newrelic (which is what is being stored in '/api/lat_long.json' does not have the final closing '}' once every orange moon. and this is what is throwing this error. my question is there any whay for me to check if the returned value is valid json and if it is not try the GET request again without terminating the process that called it. Thx

Vladimir_314159
  • 1,457
  • 1
  • 9
  • 21

1 Answers1

2

Your code is throwing an error because the json is not correct, therefore it can't be parsed, and therefore the observable throws an error:

fetchNews(): Observable<any>{
  return this.http.get(this.theUrl)
}

By default, the http client expect json because that's usually what users expect from it. It's not always the case, like the situation you are in right now.

We can tell the http client not to parse the json on its own by specifying what we want from it using the {responseType: 'text'} parameter.

fetchNews(): Observable<any>{
  return this.http.get(this.theUrl, {responseType: 'text'})
}

But then you need to parse the json when possible. So we will map the observable and parse the content here if possible.

fetchNews(): Observable<any>{
  return this.http.get(this.theUrl, {responseType: 'text'}).map(res => {
    try{ 
      return JSON.parse(res); 
    } catch {
      return null;
    }
  })
}

Then do whatever you want, the value returned by the observable will be null if it can't be parsed.


RXJS 6 syntax:

fetchNews(): Observable<any>{
  return this.http.get(this.theUrl, {responseType: 'text'}).pipe(
    map(res => {
      try{ 
        return JSON.parse(res); 
      } catch {
        return null;
      }
    })
  )
}
Ploppy
  • 14,810
  • 6
  • 41
  • 58
  • Ah what I was doing wrong was I forgot the `.map(...)` part sorry i'm very new to angular thanks so much it works. – Vladimir_314159 Jul 12 '18 at 20:59
  • 1
    Observable are not complexe, though I think they are unintuitive. Once you get them you will be able to take full advantage of them and won't even think of coding without it! – Ploppy Jul 12 '18 at 21:01
  • 1
    Note that with RXJS 6 the syntax would change slightly. I will edit the answer accordingly. – Ploppy Jul 12 '18 at 21:49