2016-11-21 33 views
1

這是從角2的http指南應用程序/ TOH/hero.service.ts:在Angular 2中response.json()做了什麼?

... 
@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) { 
    ... 
    } 

} 

請參考線讓體= 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; 
    }; 

這兩個是如何相關的?

+0

什麼不清楚你的迴應? '.json'方法試圖將響應正文解析爲JS對象。它提到[這裏](https://angular.io/docs/ts/latest/guide/server-communication.html#!#parse-to-json)*「Angular HTTP客戶端遵循Fetch規範」*。 – jonrsharpe

+0

它返回響應的解析數據... – Maxime

+0

@johnsharpe,可能我沒有妥善解決我的問題。我想知道'響應'源代碼中的哪裏可以找到json()方法。我在'Body'源代碼中找到該方法。我正在回答我自己的問題,請通讀本文,如果您發現我有任何誤解,請指出。 –

回答

3

我看了node_modules/@角/ HTTP/src目錄&不停地尋找

出口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 __()); 
}; 

所以機身擁有JSON()&響應通過複製的方式得到它從身體。

-1

類似的東西:

JSON.parse(data['_body']) 
0

只是地圖JSON()

this.jsonp.get("http://localhost:8080/api/getpost") 
      .map(res => res.json()) 
      .subscribe(data => console.log(data));