I have a simple angular2 http get call like below
import { Http, Response } from '@angular/http';
@Injectable()
export class ServiceBase {
protected resource: string;
constructor(private _http: Http) { }
getTnCByCountryCodeNdType(countryCode: string, tncType: string) {
let url = `${CONFIG.URL}/tnc?countryCode=${country}&tnc=${tnc}`;
return this._http.get(url, this.getHeader())
.map((res: Response) => {
return res.json();
});
}
}
The Error response from the above when received,
I tried
this.service
.getTnCByCountryCodeNdType('MY', this.tnc.toLowerCase())
.subscribe(x => {
//
},
(err: Response) => {
error = JSON.parse(err);
});
where: err is the response error;
and it threw the usual json error .
EXCEPTION: Unexpected token R in JSON at position 0
To my surprise
error = err.json();
Works fine. What is the difference between the two and why does the first one failed? Any help is appreciated
JSON.parse is a JavaScript thing. It parses a string containing JSON into whatever that string represents. You don't pass it objects. Clearly, your err isn't a string.
The res and err that Angular 2's http gives you are Response objects, which says it derives from Body. I can't see anything in the Angular 2 docs saying what Body is, but clearly it has a json function that returns the result of parsing the response data as JSON. That's not a JavaScript thing, that's something from Angular. (As noted in the link above, it's inspired by — but not the same as — fetch.)
JSON.parse expects a JSON-formatted string, but you give it a Response object, which is not JSON, hence the parsing error.
res.json() extracts the JSON-formatted data from the Response object and converts the data into a JavaScript object.