gyc gyc - 9 days ago 6
TypeScript Question

Put more than one expression in an arrow function

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)

Answer

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);