2

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.

james keller
  • 99
  • 2
  • 7
  • 2
    Something to read, and enjoy: https://angular.io/guide/lifecycle-hooks. Some of the links in the guide will point to resources that will answer your question. – R. Richards Mar 25 '18 at 20:33
  • Here you have good description how constructor and ngOnInit works and what is difference: https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit – Patryk Gułaś Mar 25 '18 at 20:51
  • Possible duplicate of [Difference between Constructor and ngOnInit](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit) – Zze Mar 25 '18 at 20:54
  • I'd also like to add that testing is much easier if you handle the business login in ngOnInit. – Tomasz Kula Mar 25 '18 at 21:05
  • Ok, so, correct if I'm wrong. That article says "A component constructor is the only method that is called in the context of the injector so if you need any dependency that’s the only place to get those dependencies." Since auth.handleAuth() is part of a Service, which is an app.component Dependency, that would be the place to call it? I'm trying to understand why place it there, sorry. – james keller Mar 25 '18 at 21:51
  • Or, perhaps, it's a matter of order of precedence: being an authentication function, it should be called during components tree's construction rather than during change detection running? – james keller Mar 25 '18 at 21:58

0 Answers0