I see some examples of Angular 2, which convert the response of http
into JavaScript object like this:
http.get("http://....").subscribe(
response => {
let result = response.json();
},
error => {
console.log('cannot get api');
}
);
I also see some examples which state that json()
method returns a Promise, which requires the function to be enclosed in then
to obtain the result:
response.json().then(result => ({
///
});
Why does one use then
and the other does not? What's the return of value of json
and which should I use?
The examples where you see response.json()
returning a Promise
are part of the Fetch API, which is still experimental: https://developer.mozilla.org/en-US/docs/Web/API/Response
Body.json()
Takes a Response stream and reads it to completion. It returns a promise that resolves with a JSON object.
The other example you see are from Angular's implementation which returns the data directly instead of a Promise
: https://github.com/angular/angular/blob/master/packages/http/src/body.ts#L26
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.