角度得到反应的身体

时间:2017-07-15 16:03:30

标签: angular

我无法理解如何从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究竟是什么以及我需要如何检索它的属性。

1 个答案:

答案 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());