Related to but not the same as Difference between Constructor and ngOnInit.
In Angular 16 and 17 we can now use the takeUntilDestroyed operator and Signals. Both of these seems to work best in an Injector Context or at least has an advantage that you do not need to pass one.
Question
So the question is (again) should we put initialization in the constructor (or member fields) or still use OnInit? Second are there any pitfalls in using the constructor rather than OnInit?
Note: With initialization I mean using httpClient to fetch data to display on the page. Setup RxJS pipes with mapping of data, etc. Reading Route params, etc.
Set aside the following:
- We need to use
OnInitorOnChangesif we want to use@Input()variables - Personal preference
Additional information
According to the old Angular.io site's Component Lifecycle documentation:
Components should be cheap and safe to construct. You should not, for example, fetch data in a component constructor. You shouldn't worry that a new component will try to contact a remote server when created under test or before you decide to display it. An ngOnInit() is a good place for a component to fetch its initial data.
But this documentation does not exist in the new Angular.dev site.
Also one of their new tutorials has data calls in the constructor:
constructor() { this.housingService.getAllHousingLocations().then((housingLocationList: HousingLocation[]) => { this.housingLocationList = housingLocationList; this.filteredLocationList = housingLocationList; }); } Summary
It seems Angular 16/17 is going in a direction where more initialization is done in an injection context (member field or constructor). Does that have implications on performance, stability, future development?