这是来自app / toh / hero.service.ts的角度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个如何相关?
答案 0 :(得分:3)
我查看了node_modules / @ angular / http / src&amp;一直在寻找
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 __());
};
所以身体有json()&amp;响应通过复制从Body获取。
答案 1 :(得分:0)
只需使用json()
映射您的回复this.jsonp.get("http://localhost:8080/api/getpost")
.map(res => res.json())
.subscribe(data => console.log(data));