[英]In Angular 2 what does response.json() do?
這是來自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;
};
這2個如何相關?
我查看了node_modules / @ angular / http / src並繼續搜索
export var響應
發現在文件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獲取它。
只需使用json()映射您的響應
this.jsonp.get("http://localhost:8080/api/getpost")
.map(res => res.json())
.subscribe(data => console.log(data));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.