-1

I work on code snippet described on https://angular.io/tutorial/toh-pt5

export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];
  constructor(private heroService: HeroService) { }
  ngOnInit(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));
  }
}

And my question about this code part:

.then(heroes => this.heroes = heroes.slice(1, 5));

is it possible to create a method in DashboardComponent and pass it as argument instead of function? Is the functional approach here anything better than a method inside DashboardComponent class?

P_M
  • 2,723
  • 4
  • 29
  • 62
  • 1
    Sure it's possible. `.then(this.onGetHeroes.bind(this))`. – deceze Oct 25 '17 at 11:08
  • One line arrow function seems to be used for terseness. One line instead of multiple when adding another method. – evolutionxbox Oct 25 '17 at 11:08
  • @deceze why you used bind method.? Is it not enough to put in method body this.heroes = heroes.slice(1, 5) ? – P_M Oct 25 '17 at 11:10
  • Because: [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/476) – deceze Oct 25 '17 at 11:12
  • Oh thanks! I thought this is not the case when using typescript. Probably this is my mistake. – P_M Oct 25 '17 at 11:18

1 Answers1

1

There are several reasons why using arrow functions. Most of them are just a matter of style & readability.

Beside that, there is one important difference: if you would be passing components method to it then you would need to bind contrxt for this to that method. With arrow function thats not needed as they dont create new context.

dee zg
  • 13,793
  • 10
  • 42
  • 82