2016-11-21 4 views
1

これはAPP/TOH/hero.service.tsための角度2 HTTPガイドからのものである: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(LET線を参照してください)。 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オブジェクトにパースしてあなたのためにしようとします。 *「Angular HTTPクライアントはFetch仕様に準拠しています」と記載されています(https://angular.io/docs/ts/latest/guide/server-communication.html#!#parse-to-json)。 – jonrsharpe

+0

レスポンスの解析データを返します。 – Maxime

+0

@johnsharpe、おそらく私の質問に正しく言及していません。「Response」ソースコードのどこにjson()メソッドがあるか知りたいと思います。私は 'Body'のソースコードでこのメソッドを見つけました。私は自分の質問に答えています。それを読んでください。私のところで何か誤解がある場合は、指摘してください。 –

答えて

3

私は角度@/HTTP/srcに&/node_modulesに見えたが

輸出するvar応答ファイルstatic_response.jsでことがわかっ

を探し続けました。それは言う:次のように同じファイル__extendsで

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)); 

が定義されている:

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)); 
関連する問題