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?
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) { }
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
No. Before the class is created Angular needs to know what providers it should inject, you cannot do that using the latter example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With