Angular
Search…
Dependency injection in Angular
Dependencies are services or objects that a class needs to perform its function. Dependency injection, or DI, is a design pattern in which a class requests dependencies from external sources rather than creating them.

What are the services?

A Service is a broad category encompassing any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well. Angular distinguishes components from services to increase modularity and reusability. By separating a component's view-related functionality from other kinds of processing, you can make your component classes lean and efficient.

Service examples

Here's an example of a service class that logs to the browser console.src/app/logger.service.ts (class)
1
content_copyexport class Logger {
2
log(msg: any) { console.log(msg); }
3
error(msg: any) { console.error(msg); }
4
warn(msg: any) { console.warn(msg); }
5
}
Copied!
Services can depend on other services. For example, here's a HeroService that depends on the Logger service, and also uses BackendService to get heroes. That service in turn might depend on the HttpClient service to fetch heroes asynchronously from a server.src/app/hero.service.ts (class)
1
content_copyexport class HeroService {
2
private heroes: Hero[] = [];
3
4
constructor(
5
private backend: BackendService,
6
private logger: Logger) { }
7
8
getHeroes() {
9
this.backend.getAll(Hero).then( (heroes: Hero[]) => {
10
this.logger.log(`Fetched ${heroes.length} heroes.`);
11
this.heroes.push(...heroes); // fill cache
12
});
13
return this.heroes;
14
}
15
}
Copied!