Angular Response.json() not documented

If you look at the API Reference for Response, you'll see that Response extends Body. If you try to search for Body, you won't find it, which probably means it isn't public. If you look at the source code for Body, you'll see the code for json

/**
 * Attempts to return body as parsed `JSON` object, or raises an exception.
 */
json(): any {
  if (typeof this._body === 'string') {
    return JSON.parse(<string>this._body);
  }

  if (this._body instanceof ArrayBuffer) {
    return JSON.parse(this.text());
  }

  return this._body;
}

Let me know if you need explanation of the source. It looks pretty self-explanitory to me though.


Actually, the HTTP Client documentation (Process the response object) says:

Parse to JSON

This is not Angular's own design. The Angular HTTP client follows the Fetch specification for the response object returned by the Fetch function. That spec defines a json() method that parses the response body into a JavaScript object.

So Angular2 implements the Fetch Specification, which includes the specification for the mentioned Body mixin, Angular2's Response class is extending, including the .json() method.

The json() method, when invoked, must return the result of running consume body with JSON.

As you can see in peeskillet's link, Angular2 is implementing all specified methods of the Body mixin, except of formData().


I had the same problem and this is how the error go away: In the new version of Angular 4+, you need to imports rxjs from:

import { map } from 'rxjs/operators';

instead of from importing from:

import 'rxjs/add/operator/map';

Next, change the .get() to .get() and also you have to use pipe for angular 4+ as below:

getCurrentTime() {
    return this._http.get<any>('http://date.jsontest.com/')
        .pipe(map((res:Response) => res.json()));
}

Hope that Helps...!

Tags:

Json

Angular