-1

https://angular.io/guide/dependency-injection

A provider tells an injector how to create the service. You must configure an injector with a provider before that injector can create a service (or provide any other kind of dependency).

This code is also from that link:

import { Injectable } from '@angular/core';
import { HEROES } from './mock-heroes';

@Injectable({
  // we declare that this service should be created
  // by the root application injector.
  providedIn: 'root',
})
export class HeroService {
  getHeroes() { return HEROES; }
}

Here 'root' is the injector. Who is the provider?

The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule.

In my code I have directly imported a service as follows and injected it in the constructor:

import { BlogContentsService } from '../blog-contents.service'

...

constructor( private objBlogContentsService: BlogContentsService)
{ 
}

This is working properly. I haven't specified any provider anywhere.

How do I specify a provider here? Why is it working without me specifying a provider in my class?

In my app.module.ts,

@NgModule({
  declarations: 
  [
    AppComponent,
    TitleBodyFormComponent,
    DashboardComponent,
    MyElseDirective,
    ElseDirective,
    WhitespaceValidatorDirective    
  ],
  imports: 
  [
    BrowserModule,
    AppRoutingModule,
    // ------ Added by me for reactive forms:
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

providers:[] list is empty.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

1

When you have providedIn:'root' there this service is automatically injected into root injector. And is available throughout application. But if you remove that 'providedIn': 'root' from the decorator. You will be required to import it in providers array, where you want it.

This providedIn: 'root' was introduced with concept of treeshakable providers in angular.

More details can be found at :- https://coryrylan.com/blog/tree-shakeable-providers-and-services-in-angular

Aakash Garg
  • 10,649
  • 2
  • 7
  • 25