Answer the question
In order to leave comments, you need to log in
Why use a provider in a component?
As you know, in order to inject a certain class into another class in angular, you need to use something like this:
import { Component } from '@angular/core';
import { HeroServiceProvider } from './hero.service.provider';
@Component({
selector: 'app-heroes',
providers: [ HeroServiceProvider ],
template: `
<h2>Heroes</h2>
<app-hero-list></app-hero-list>
`
})
export class HeroesComponent {
constructor(private heroServiceProvider: HeroServiceProvider);
}
Answer the question
In order to leave comments, you need to log in
1. Import means nothing. It's just getting a reference to the current scope. This is what webpack does.
2. providers - an indication to the injector that he should know about such entities. In this case, for a local injector that the current component and its nested components have access to.
This injector is created before the component is created and dies after. Also, when dying, the ngOnDestroy hook will be called for all provider instances in this injector.
3. By specifying the type in the constructor, we tell the injector what data we want to receive (here HeroServiceProvider is a token, because it is a pointer), before creating an instance of the class, specifically HeroesComponent.
The injector looks to see if it has such, and if not, it creates and passes it to the constructor. The HeroServiceProvider instance will be created and only visible in the HeroesComponent or its nested components.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question