Reputation: 4360
I have data returned from an http.get (function in a service)
return this.http.get('https://randomuser.me/api/').toPromise().then(
response => response.json().results as User[]
).catch(this.handleError);
In the component I call this service and set my model to the json result
ngOnInit(): void {
this.userService.getUser().then(
users => this.users = users
);
}
In the template I can just use {{user.email}}
to get the email.
Now if I try to add a line of code inside the http promise.then
return this.http.get('https://randomuser.me/api/').toPromise().then(
response => {
response.json().results as User[];
console.log(response);
}
).catch(this.handleError);
The console show the response object, but user.email is not displayed in the page anymore. (no error in the consoles)
Upvotes: 1
Views: 300
Reputation: 13216
Arrow functions either take a single expression, and implicitly return the result, or a series of statements, with no implicit return. See the MDN article on arrow functions for more detail. To fix this, you need to explicitly return response.json().results
at the end of your arrow function:
return this.http.get('https://randomuser.me/api/').toPromise().then(
response => {
console.log(response);
return response.json().results as User[];
}
).catch(this.handleError);
Upvotes: 2
Reputation: 123861
Just add return
statement
return this.http.get('https://randomuser.me/api/').toPromise().then(
//response => {
// response.json().results as User[];
// console.log(response);
//}
response => {
console.log(response);
// we have to return something here
return response.json().results as User[];
}
).catch(this.handleError);
Upvotes: 0