简体   繁体   English

角度得到反应的身体

[英]Angular getting response body

I'm having trouble understanding how one is supposed to get the response body from an Angular Response object. 我无法理解如何从Angular Response对象获取响应主体。 In their docs they have an example that states 在他们的文档中,他们有一个例子说明

http.request('my-friends.txt').subscribe(response => this.friends = response.text());

yet when I attempt to do let body: string = response.text(); 然而,当我尝试做let body: string = response.text(); I get an error saying "Argument of type 'Promise' is not assignable to parameter of type 'string'". 我得到一个错误,说“类型'承诺'的参数不能分配给'string'类型的参数”。

I tried treating it as a promise and doing 我试着将它视为承诺和行动

let body: string; response.text().then(text => body = text);

which removes the compilation error, but when this code gets invoked it throws and error saying "TypeError: response.text(...).then is not a function". 这会删除编译错误,但是当调用此代码时,它会抛出错误,并显示“TypeError:response.text(...)。然后它不是函数”。

I would like to understand what exactly a Promise is and how I need to retrieve it's properties. 我想了解Promise究竟是什么以及我需要如何检索它的属性。

I believe you've referenced the wrong Response object in your imports. 我相信你在导入中引用了错误的Response对象。 If you're specifying the type need to import Response object from Angular package: 如果您要指定类型需要从Angular包导入Response对象:

import { Response } from '@angular/http`;

There is also Response object from fetch API supported natively by browsers. 浏览器本身也支持fetch API的Response对象。 They differ in that Angular Response object returns string for Response.text() method, while fetch API Response returns a promise. 它们的不同之处在于Angular Response对象返回Response.text()方法的string ,而fetch API Response返回一个promise。 The http service uses Angular's Response object and it returns a string so you don't need a promise here. http服务使用Angular的Response对象,它返回一个字符串,这样你就不需要一个promise。

If you want to save the body text to the body variable, you have to do it when you get the value from an observable: 如果要将正文保存到body变量,则必须在从observable获取值时执行此操作:

http.request('my-friends.txt').subscribe((response: Response) => this.body = response.text());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM