I'm having trouble understanding how one is supposed to get the response body from an Angular Response object. 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();
I get an error saying "Argument of type 'Promise' is not assignable to parameter of type '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".
I would like to understand what exactly a Promise is and how I need to retrieve it's properties.
I believe you've referenced the wrong Response
object in your imports. If you're specifying the type need to import Response object from Angular package:
import { Response } from '@angular/http`;
There is also Response object from fetch API supported natively by browsers. They differ in that Angular Response
object returns string
for Response.text()
method, while fetch API Response
returns a promise. The http
service uses Angular's Response
object and it returns a string so you don't need a promise here.
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:
http.request('my-friends.txt').subscribe((response: Response) => this.body = response.text());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.