Angular: function calling on constructor

时间:2018-03-25 20:21:33

标签: angular constructor auth0 ngoninit

I'm following this auth0 tutorial, and it says there:

The authentication service's handleAuth() method must be called in the app.component.ts constructor so it will run on initialization of our app:

// src/app/app.component.ts
import { AuthService } from './auth/auth.service';
...
  constructor(private auth: AuthService) {
    // Check for authentication and handle if hash present
    auth.handleAuth();
  }
...

However, documentations and answers like this one say:

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

In the tutorial, the author does uses ngOnInit on app.component.ts to run code that deals with the responsive part of the layout:

// src/app/app.component.ts
 ngOnInit() {
      Observable.fromEvent(window, 'resize')
        .debounceTime(200)
        .subscribe((event) => this._resizeFn(event));

      this._initWinHeight = window.innerHeight;
      this._resizeFn(null);

    }

Why use different initialization methods? Does the function calling inside the constructor, in this case, serves some purpose?

And, please, correct me if I'm saying anything wrong. I'm new to this. Any input is appreciated.

0 个答案:

没有答案