gpt4 book ai didi

javascript - 在 Angular 2 中,response.json() 是做什么的?

转载 作者:行者123 更新时间:2023-11-30 11:46:46 25 4
gpt4 key购买 nike

这是来自 app/toh/hero.service.ts 的 angular 2 http 指南:

...
@Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web API
constructor (private http: Http) {}
getHeroes (): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
...
}

}

请引用 let body = res.json();从 API 中,我无法在 Response 对象上找到任何 json() 方法。从响应源我确实找到了这个:

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

这两个有什么关系?

最佳答案

我查看了 node_modules/@angular/http/src 并一直在寻找

export var Response

在文件 static_response.js 中发现。它说:

export var Response = (function (_super) {
__extends(Response, _super);
function Response(responseOptions) {
_super.call(this);
this._body = responseOptions.body;
this.status = responseOptions.status;
this.ok = (this.status >= 200 && this.status <= 299);
this.statusText = responseOptions.statusText;
this.headers = responseOptions.headers;
this.type = responseOptions.type;
this.url = responseOptions.url;
}
Response.prototype.toString = function () {
return "Response with status: " + this.status + " " + this.statusText + " for URL: " + this.url;
};
return Response;
}(Body));

在同一个文件中__extends定义如下:

var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

所以 Body 有 json() & Response 通过复制的方式从 Body 中获取。

关于javascript - 在 Angular 2 中,response.json() 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com