Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Response.json() not documented

Tags:

json

angular

I see Response.json() method being used a lot, and I'm using it myself, but either I'm missing something or the documentation for the Response class is incorrect.

Example:

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

On the Angular site at https://angular.io/docs/ts/latest/api/http/index/Response-class.html, I don't see the method as a member of the Response class.

If .json is not a member of the Response class, can someone point me in the direction of understanding how this works.

Or if the documentation is wrong, someone please say so.

Thanks in advance.

like image 912
BBaysinger Avatar asked Dec 24 '16 02:12

BBaysinger


People also ask

What does Response json() return?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

What does json() do?

It is a text-based way of representing JavaScript object literals, arrays, and scalar data. JSON is relatively easy to read and write, while also easy for software to parse and generate. It is often used for serializing structured data and exchanging it over a network, typically between a server and web applications.


2 Answers

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.

like image 160
Paul Samsotha Avatar answered Oct 04 '22 08:10

Paul Samsotha


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

like image 10
naeramarth7 Avatar answered Oct 04 '22 07:10

naeramarth7