I know in general, one should instantiate instance variables and dependencies in the constructor, whether it is injected, new
'ed up, or from a @ngrx/store
select()
:
@Component
export class MyCoolComponent implements OnInit {
public coolObservable$: Observable<any>;
public myItems$: Observable<Item[]>;
constructor(private myCoolService: CoolService, private store: Store) {
// Instantiate the Observables here?
this.coolObservable$ = Observable.of('cool!');
this.myItems$ = this.store.select('items');
}
public ngOnInit() {
// Or instantiate the Observables here?
this.coolObservable$ = Observable.of('cool!');
this.myItems$ = this.store.select('items');
}
}
What is the best practice in Angular
?
The constructor() should only be used to initialize class members but shouldn't do actual "work". So we should use constructor() to setup Dependency Injection, Initialization of class fields etc. ngOnInit() is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.
OnInit : ngOnInit is component's life cycle hook which runs first after constructor(default method) when the component is being initialized. So, Your constructor will be called first and Oninit will be called later after constructor method.
ngOnInit() method usage in Angular As explained above Angular calls ngOnInit when it finishes creating a component DOM. And we will use constructors to inject all required dependencies and processed input bindings. So we have everything in place so put actual logic in ngOnInit() method.
Here if we use an @Input decorator for passing value from the parent component to the child component, the constructor will let the @Input property initialize before the component view is set up. ngOnInit (), on the other hand, is invoked after the component is initialized.
ngOnInit()
is used to make sure that the component's properties you use are already initialized. For example, in the following code invoking in the constructor getProductById()
that returns an Observable
would be wrong as the property productId
would be undefined:
@Input() productId: number;
constructor(private productService: ProductService) {}
ngOnInit() {
this.product = this.productService.getProductById(this.productId);
}
But in your case, you just initialize two variables in the constructor without using any component properties, so keeping this code in the constructor is fine.
Having said that, some purists would frown upon having any code in the constructor, but purists are not always right :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With