[英]Getting a Full Response (not just the body) from Angular 4 HTTP Calls
[英]Angular getting response body
我无法理解如何从Angular Response对象获取响应主体。 在他们的文档中,他们有一个例子说明
http.request('my-friends.txt').subscribe(response => this.friends = response.text());
然而,当我尝试做let body: string = response.text();
我得到一个错误,说“类型'承诺'的参数不能分配给'string'类型的参数”。
我试着将它视为承诺和行动
let body: string; response.text().then(text => body = text);
这会删除编译错误,但是当调用此代码时,它会抛出错误,并显示“TypeError:response.text(...)。然后它不是函数”。
我想了解Promise究竟是什么以及我需要如何检索它的属性。
我相信你在导入中引用了错误的Response
对象。 如果您要指定类型需要从Angular包导入Response对象:
import { Response } from '@angular/http`;
浏览器本身也支持fetch API的Response对象。 它们的不同之处在于Angular Response
对象返回Response.text()
方法的string
,而fetch API Response
返回一个promise。 http
服务使用Angular的Response
对象,它返回一个字符串,这样你就不需要一个promise。
如果要将正文保存到body
变量,则必须在从observable获取值时执行此操作:
http.request('my-friends.txt').subscribe((response: Response) => this.body = response.text());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.