Defining ngOnInit() with a lambda?

26 views
Skip to first unread message

jeanpierr...@googlemail.com

unread,
Jun 6, 2017, 3:26:33 AM6/6/17
to Angular and AngularJS discussion

Hi,

I have just done the Tour of Heroes and I am wondering about ngOnInit().

Why I can implement ngOnInit() like this:
ngOnInit() { this.getHeroes(); }

But not like this:
ngOnInit = () => this.getHeroes();

Or even like this:
ngOnInit = this.getHeroes;

When I use one of the latter two ways, the app will compile and run without errors, but no heroes will be loaded.

Working Plunk: https://plnkr.co/edit/ASATGPSt7iiBdDJ80tzu?p=preview
Broken Plunk: https://plnkr.co/edit/ASATGPSt7iiBdDJ80tzu?p=preview

Being used to functional programming, I prefer the latter implementations, since they do not require using a special syntax for something, that is really just an assignment.

Thanks for your help,
Nuvanda

Sander Elias

unread,
Jun 6, 2017, 4:06:49 AM6/6/17
to Angular and AngularJS discussion
Hi Nuvanda,

You didn't link your broken plunk, so It's a kind of hard to give an explanation why it doesn't work. I highly suspect that it's a side-effect off transpiling. Are you compiling down to ES5? if so, try compiling to es2015 and see if it's still the case.
The problem probably is order. TS moves the assignments you do in the class itself into the constructor. Those are then not known before you initialize the class. As the life-cycle hooks get's detected by a decorator, the detection runs before the class is initialised.

Does that explain this enough for you? if not, don't hesitate to ask!
Regards
Sander
Reply all
Reply to author
Forward
0 new messages