Angular Injector
Written By: Avinash Malhotra
Updated on
Injector plays very important role in Angular Dependency Injection. It manage and provide dependencies in Angular Application. @Injectable decorator is used in service.ts file. @Injectable decorator also includes providedIn property with default value root.
Injector can be configured at following levels
- Service level
- Component Level
- Module Level
Injectable
@Injectable Decorator is used in service. The providedIn property in @Injectable decorator provides or inject service at root, component or service level. The default value is root.
app.service.ts
<!--app.service.ts-->
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AppService {
constructor() { }
}
providedIn root
providedIn root means the service is available at App root level and is available in whole application. All the components can use same service. Adding service again in some module will be ignored.
Component
Services can be injected in particular component level. This is possible by using service in component decorator's providers array.
<!--app.component.ts-->
import { Component } from '@angular/core';
import { appService } from './error.service';
@Component({
selector: 'app-root',
standalone: true,
imports:[],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
providers: [ AppService ]
})
export class AppComponent {
title = 'myApp';
}