2

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

2
  • 3
    err is not defined or even declared in the code you've provided Commented Apr 27, 2017 at 9:49
  • @Quentin its an angular 2 service. Please i update code above. Commented Apr 27, 2017 at 10:00

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Crowder thanks for the answer. Please i updated my code above.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.