Is there a opinion on when to put data in the constructor vs when to just place it in the class? I know that if it has to do with DI then it should be in the constructor but for instance:
I have no idea if the content is a âbest practiceâ, but someone wrote a blog post on this topic:
And some more on SO:
So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to âstartâ - itâs where/when componentsâ bindings are resolved.
lol so itâs either do the initial âworkâ inside ngOnInit or inside the constructor within the platform.ready promise. Got it, neither case shows initializing variables openly inside the classâŚbut I assume itâs fine to do from the SO response â(actually implementing OnInit is not mandatory but considered good practice)â. And as far as defining the type goes, that is just an optional TS feature?
Well, platform would also be available in ngOnInit - this might also have been an (unconscious?) choice done by some Ionic dev⌠As all these posts describe both works, itâs just a question of style and choice and⌠moon phase?
You can/should initialize variables inside the constructor (which is the same as initializing them âaboveâ the constructor) in the sense of example: string[] = new Array<string>();
But performing computation in general is best done in ngOnInit() or ngAfterViewInit(). A big part of the reason for this in Ionic is that then the page preloads faster. So the rule of thumb is to keep the constructor as light weight as possible.
I see, because typically constructor is called before ngOnInit? So itâs a chance to get the variable initialized earlier in the overall component lifecycle?
Always. First you construct the page. Then, once the page is initialized, then ngOnInit() is entered. If you ensure all your variables are defined you avoid a lot of annoying Javascript undefined property errors. So itâs simpler to code pages if you make that part of your work habit. Or at least Iâve found that to be true.
Others have already covered most of the ground here, but a couple additional observations:
Magical properties that are filled by the framework (@ViewChild, @Input) cannot be interacted with in the constructor. They can only be accessed from specific lifecycle events.
Of OPâs three options, I prefer #2. While itâs certainly a great habit to be typing things, in this situation TypeScript can infer from the initialization that text is of type string, and so while #3 isnât necessarily bad, it would make a reader wonder whether something unusual is going on. #1 I do think is (relatively) bad, because it forces a reader to look in two separate places to see type and initial value, and also enables forgetting to set the initial value at all if itâs not done while declaring the property.