我无法理解如何从Angular Response对象获取响应主体。在他们的文档中,他们有一个说明
的例子 http.request('my-friends.txt').subscribe(response => this.friends = response.text());
然而,当我尝试let body: string = response.text();
时,我收到错误提示"类型' Promise'不能分配给' string'"类型的参数。
我尝试将其视为承诺和做事
let body: string;
response.text().then(text => body = text);
删除了编译错误,但是当调用此代码时,它会抛出并且错误说" TypeError:response.text(...)。那么它不是函数"。
我想了解Promise究竟是什么以及我需要如何检索它的属性。
答案 0 :(得分:1)
我相信您在导入中引用了错误的Response
对象。如果您要指定类型需要从Angular包导入Response对象:
import { Response } from '@angular/http`;
浏览器本身也支持来自fetch API的Response个对象。它们的不同之处在于Angular Response
对象为string
方法返回Response.text()
,而fetch API Response
则返回一个promise。 http
服务使用Angular的Response
对象,它会返回一个字符串,因此您不需要承诺。
如果要将正文保存到body
变量,则必须在从observable获取值时执行此操作:
http.request('my-friends.txt').subscribe((response: Response) => this.body = response.text());