In the example code you provided,to return a list of heros, we have to write it like
getHeroes(): Hero[] {
this.heroService.getHeroes()
.subscribe(heroes => ({heroes : heroes}));
}
Above arrow function will translate to
f( heroes )
{
return this.heroes = heroes;
}
Otherwise, the code you provided, its just making an assignment to this.heros variable, so return statement does not apply, and the arrow function translate to
f( heroes )
{
this.heroes = heroes;
}
Further explanation of Arrow function
Arrow functions, like function expressions, can be used to return an object literal expression. The only caveat is that the body needs to be wrapped in parentheses, in order to distinguish between a block and an object (both of which use curly brackets).
Example
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}
For a regular function, if the ‘this’ keyword were inside an object’s method (a function that belongs to an object), it would refer to the object. While in an arrow function, ‘this’, always references the owner of the function it is in. Adding a console.log(this) before the return in the arrow function returns a Window object.
Example
// ES5
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: function() {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
brunch.order(); //"I'll have the Dim sum with Jasmine tea please."
// ES6
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: () => {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
brunch.order(); //"I'll have the undefined with undefined please."