1

I have read on constructor and ngOnInit. And myself have came to a conclusion that we should make variable and service initialization in constructor and any logic in ngOnInit. And this seems clean to me.

Here is my sample of implementation. Hope to get some feedback if i am doing it right or i am understanding the constructor and ngOnInit wrongly. Or should i just put everything on ngOnInit instead.

constructor(
    public loading: LoadingController,
    public auth: AuthService,
    public data: DataService
) {
    this.existingProfile = new EventEmitter<Profile>();
    this.loader = this.loading.create({
        content: 'Loading...'
    });
}

ngOnInit() {
    this.loader.present();
    this.data.getProfile().subscribe(profile => {
        this.userProfile = profile;
        this.existingProfile.emit(this.userProfile);
        this.loader.dismiss();
    });
}
stackdisplay
  • 1,949
  • 6
  • 29
  • 46

1 Answers1

2

I've described the difference between constructor and ngOnInit in the article The essential difference between Constructor and ngOnInit in Angular in great details and this answer.

If your initialization depends on the @Input bindings then you have only one choice - ngOnInit - since bindings are not available in the constructor. If it's not dependent, then it's perfectly fine to perform initialization in the constructor. In fact, if you use outputs then this:

class O {
    @Output ev = new EventEmitter();

is still compiled to

class O {
    constructor() {
        this.ev = new EventEmitter();

However, the general recommendation is to use ngOnInit for initialization. In this way everybody on your team knows to look inside ngOnInit to understand how this component is initialized.

So as you see it's a bit subjective if there's no dependency on ngOnInit.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488