The answers on this topic I found are about 7 years old. In summary, it's recommended to use constructor for basic property initialization, setup Dependencies Injection and tasks which are not to complex. Use ngOnInit
for more complex initialization that involves interaction with services as http requests, @Input communication mechanism, or other Angular-specific operations.
Now it's recommended to use new inject
function to handle angular DI, because you may encounter issues with es2022. Are the following code snippets are only a question of style or is there any other difference?
export class ExampleComponent {
private service = inject(Dependency);
}
export class ExampleComponent {
private service: Dependency;
constructor( ) {
this.service = inject(Dependency);
}
Is it recommended to pass a subscriber function inside the constructor or is this operation also a complex thing that should be defined inside ngOnInit
function?
export class ExampleComponent {
private subscription: Subscription;
private service = inject(Dependency);
constructor( ) {
this.subscription = this.service.getAnObservable().subscribe(result => {
//do something on result
});
}