Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
In Angular dependency injection (Dependency Injection, DI) is built on injector hierarchy, where dependencies can be available:
Angular creates injector tree, similar to component tree. Each component can have own injector, inherited from parent.
@Injectable({ providedIn: 'root' })providers.@Injectable({ providedIn: 'root' })
export class LoggerService {}
Used by default for singleton services.
@NgModule({
providers: [AuthService]
})
export class AuthModule {}
Good for limited access and lazy-loaded modules.
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
providers: [CartService]
})
export class CartComponent {}
For each component usage new instance of service will be created.
@Directive({
selector: '[highlight]',
providers: [HighlightService]
})
export class HighlightDirective {}
When Angular injects dependency, it:
root).@Component({
selector: 'parent',
providers: [SharedService],
template: `<child></child>`
})
export class ParentComponent {}
@Component({
selector: 'child',
template: `...`
})
export class ChildComponent {
constructor(shared: SharedService) {} // will get instance from parent
}
If SharedService is not specified in child, it will be inherited from parent.