Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Service Why are we injecting on constructor

Tags:

angular

Why are we injecting service in constructor as a parameter like this?

import { HeroService } from '../hero.service'; 
constructor(private heroService: HeroService) { }

Instead of passing as a parameter, why don't we inject inside constructor:

import { HeroService } from '../hero.service'; 
constructor() {
    this.heroService=HeroService;
}

Is it possible to do in the above way?

like image 668
Chellappan வ Avatar asked Mar 06 '23 11:03

Chellappan வ


2 Answers

As, you can find in official docs,

The parameter simultaneously defines a private heroService property and identifies it as a HeroService injection site.

constructor(private heroService: HeroService) { }
  • When Angular creates a HeroesComponent, the Dependency Injection system sets the heroService parameter to the singleton instance of HeroService.
  • You can tell Angular to inject a dependency in the component's constructor by specifying a constructor parameter with the dependency type. Here's the HeroListComponent constructor, asking for the HeroService to be injected.

Note:

  • The component shouldn't create the HeroService with new. It should ask for the HeroService to be injected.

  • You can tell Angular to inject a dependency in the component's constructor by specifying a constructor parameter with the dependency type. Here's the HeroListComponent constructor, asking for the HeroService to be injected.

What happens if we dont follow that:

If you donot want to use depenedency injection, you should create new instance of service everytime with required dependencies, which is something we dont want.

Also, we need to declare a new variable for that service

Eg:

export class HeroListComponent {
  heroes: Hero[];
  heroService;
  constructor()
  {
    this.heroService = new HeroService('', '');
    this.heroes = this.heroService.getHeroes();
  }
}

Here is a reference for the same

like image 97
Sravan Avatar answered Mar 20 '23 03:03

Sravan


No. Before the class is created Angular needs to know what providers it should inject, you cannot do that using the latter example.

like image 41
bc1105 Avatar answered Mar 20 '23 03:03

bc1105