When generating services in the Angular CLI, it is adding extra metadata with a \'provided in\' property with a default of \'root\' for the Injectable decorator.
<
see Excellent explanation by @Nipuna,
I'd like to extend it by adding examples.
if you just use Injectable decorator without providedin property, like,
@Injectable()
then you would have to write service's name in respective Module's providers Array.
like this;
data.service.ts ↴
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
constructor() {}
// Code . . .
}
app.module.ts ↴
import { AppComponent } from './app.component';
import { DataService } from './core/data.service';
@NgModule({
declarations: [AppComponent],
providers: [DataService], // ⟵ LOOK HERE WE PROVIDED IT
imports: [...],
bootstrap: [AppComponent],
})
export class AppModule {}
But, If you use providedIn: 'root', like this:
data.service.ts ↴
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class DataService {
constructor() {}
// Code . . .
}
Then our module would look like this:
app.module.ts ↴
import { AppComponent } from './app.component';
import { DataService } from './core/data.service';
@NgModule({
declarations: [AppComponent],
providers: [],
imports: [...],
bootstrap: [AppComponent],
})
export class AppModule {}
see I did't add DataService in providers array this time, because it's not needed.