Z
Z
zlodiak2022-01-04 21:51:18
Angular
zlodiak, 2022-01-04 21:51:18

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);
}

3 points are important here:

  1. there must be an import
  2. the imported class must be registered in the providers array
  3. in the constructor, using the simplest syntactic sugar, assign the object of the injected class to the local variable of the component.


Please explain why point 2 is needed in this chain? That is, it is clear that if the injected class is not placed in the providers array, then the framework will throw an exception, but I would like to understand the very meaning of this room.

Why don't framework developers make it so that programmers, after importing the injected class, would immediately give it through the component's local variable constructor?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shvets, 2022-01-08
@zlodiak

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.

P
Pavel Shvedov, 2022-01-04
@mmmaaak

https://metanit.com/web/angular2/4.5.php

S
Sergey, 2022-01-04
@KingstonKMS

Importing a provider into a file means absolutely nothing. Specifying providers in the decorator parameters is necessary for the correct construction of the dependencies of the entire project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question