Angular Dependency Injection¶
Note
Dependency Injection is a design pattern that separates dependencies of a class from its environment. It is used to provide services, components and dependencies. DI containers create instances of dependencies.
Service¶
ng generate service <service-name>
@Injectable({
providedIn: 'root',
})
class Service {}
Note: providedIn: 'root'
is used to make the service available to the entire application as Singleton Instance.
@Component({
selector: 'component',
template: '...',
providers: [Service]
})
class ComponentClass {}
@NgModule({
declarations: [ComponentClass],
imports: [CommonModule],
providers: [Service]
})
class ModuleClass {}