Angular: function calling on constructor

一世执手 提交于 2021-01-28 08:21:48

问题


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.

来源:https://stackoverflow.com/questions/49480549/angular-function-calling-on-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!