简体   繁体   English

.json()函数在Angular2中做什么?

[英]What does .json() function do in Angular2?

What does the .json() function in http requests in Angular2 do? Angular2的http请求中的.json .json()函数有什么作用?

Example code: 示例代码:

this.http.get('http://localhost:8080/getName')
.subscribe(res => this.names = res.json());

I guess it's similar to javascript's JSON.parse() ? 我想这类似于javascript的JSON.parse()吗?

This function takes a response from the Http call, and parses it (just like JSON.parse(..)). 此函数从Http调用获取响应,并对其进行解析(就像JSON.parse(..)一样)。 Notice, if the return is not json, it will throw an error. 请注意,如果return不是json,它将引发错误。

You can check the source code to see what it does. 您可以检查源代码以查看其功能。 But as @uksz said, it just parses the json, using JSON.parse 但是正如@uksz所说的,它只是使用JSON.parse解析json。

The source code is this: 源代码是这样的:

    /**
     * Attempts to return body as parsed `JSON` object, or raises an exception.
     */
    Body.prototype.json = function () {
        if (typeof this._body === 'string') {
            return JSON.parse(this._body);
        }
        if (this._body instanceof ArrayBuffer) {
            return JSON.parse(this.text());
        }
        return this._body;
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM