-1

I need clarification of on variable assignment in an Angular service,

I am new to Angular and I wish to have a deep understanding of the implications if any of assigning a variable in these three locations as illustrated bellow.

Case 1

    import { Injectable, OnInit } from "@angular/core";

    @Injectable({
      providedIn: 'root'
    })
    export class FavoriteMovieService implements OnInit {

      sampleArray;    

      constructor() {
        this.sampleArray = [1, 2, 3, 4, 5];
      }

      ngOnInit() { }
    }

Case 2

    import { Injectable, OnInit } from "@angular/core";

    @Injectable({
      providedIn: 'root'
    })
    export class FavoriteMovieService implements OnInit {

      sampleArray;    

      constructor() {}

      ngOnInit() {
        this.sampleArray = [1, 2, 3, 4, 5];
      }
    }

Case 3

    import { Injectable, OnInit } from "@angular/core";

    @Injectable({
      providedIn: 'root'
    })
    export class FavoriteMovieService implements OnInit {

      sampleArray = [1, 2, 3, 4, 5];;    

      constructor() {}

      ngOnInit() {}
    }

Version information

  Angular CLI: 8.3.5
Node: 10.15.3
OS: win32 x64
Angular: 8.2.7
wokoro douye samuel
  • 2,194
  • 3
  • 15
  • 29

1 Answers1

1

Before adding the differences, please note that the ngOnInit won't work at all in your case. It won't get called.

The only lifecycle hook that will work with the services is the ngOnDestroy, which will be called when the service got destroyed. All other lifecycle hooks like the ngOnInit won't get called as they will only get called for the components and directives.

I will add the differences and include the ngOnInit if it is implemented inside a component / directive instead.

For the differences between the constructor assignments and inline direct assignments, from here:

Both are correct programming wise,

Initialized within the constructor

It would be good practice to initialized within the constructor , it's kind of code separation of declaration + initialization .

That will increase your code readability and you will be sure that all values initialized within the constructor only. and because in the constructor is when the object is created, and it is when the variable should initialized.


Initialized outside the constructor

One issue with initialized using the constructor is , more code to write , when you have alot variable to work with , in that case you should use direct counter: number = 1 , In this case you can check declaration + initialization in single line , but in above case you have to go through 2 steps declaration + initialization

It really matters when you choose initialisation within one of the life cycle hook (E.g. NgOnInit / NgAfterViewInit) vs the constructor. Either it's just a coding style

For the constructor and ngOnInit hook, from here:

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better Dependency Injector (DI) analyzes the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like

new MyClass(someArg);

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice):

import {Component, OnInit} from '@angular/core';

then to use the method of OnInit we have to implement in the class like this.

export class App implements OnInit{
  constructor(){
     //called first time before the ngOnInit()
  }

  ngOnInit(){
     //called after the constructor and called  after the first ngOnChanges() 
  }
}

Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

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".

So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

For more information refer here:

yazantahhan
  • 2,950
  • 1
  • 13
  • 16