{ "id": "guide/architecture-services", "title": "Introduction to services and dependency injection", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Introduction to services and dependency injectionlink

\n

Service is a broad category encompassing any value, function, or feature that an app needs.\nA service is typically a class with a narrow, well-defined purpose.\nIt should do something specific and do it well.

\n

Angular distinguishes components from services to increase modularity and reusability.\nBy separating a component's view-related functionality from other kinds of processing,\nyou can make your component classes lean and efficient.

\n

Ideally, a component's job is to enable the user experience and nothing more.\nA component should present properties and methods for data binding,\nin order to mediate between the view (rendered by the template)\nand the application logic (which often includes some notion of a model).

\n

A component can delegate certain tasks to services, such as fetching data from the server,\nvalidating user input, or logging directly to the console.\nBy defining such processing tasks in an injectable service class, you make those tasks\navailable to any component.\nYou can also make your app more adaptable by injecting different providers of the same kind of service,\nas appropriate in different circumstances.

\n

Angular doesn't enforce these principles. Angular does help you follow these principles\nby making it easy to factor your application logic into services and make those services\navailable to components through dependency injection.

\n

Service exampleslink

\n

Here's an example of a service class that logs to the browser console.

\n\nexport class Logger {\n log(msg: any) { console.log(msg); }\n error(msg: any) { console.error(msg); }\n warn(msg: any) { console.warn(msg); }\n}\n\n\n\n

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.

\n\nexport class HeroService {\n private heroes: Hero[] = [];\n\n constructor(\n private backend: BackendService,\n private logger: Logger) { }\n\n getHeroes() {\n this.backend.getAll(Hero).then( (heroes: Hero[]) => {\n this.logger.log(`Fetched ${heroes.length} heroes.`);\n this.heroes.push(...heroes); // fill cache\n });\n return this.heroes;\n }\n}\n\n\n\n

Dependency injection (DI)link

\n\"Service\"\n

DI is wired into the Angular framework and used everywhere to provide new components with the services or other things they need.\nComponents consume services; that is, you can inject a service into a component, giving the component access to that service class.

\n

To define a class as a service in Angular, use the @Injectable() decorator to provide the metadata that allows Angular to inject it into a component as a dependency.\nSimilarly, use the @Injectable() decorator to indicate that a component or other class (such as another service, a pipe, or an NgModule) has a dependency.

\n\n

For any dependency that you need in your app, you must register a provider with the app's injector,\nso that the injector can use the provider to create new instances.\nFor a service, the provider is typically the service class itself.

\n
\n

A dependency doesn't have to be a service—it could be a function, for example, or a value.

\n
\n

When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. For example, the constructor of HeroListComponent needs HeroService.

\n\nconstructor(private service: HeroService) { }\n\n\n

When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.

\n

When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.

\n

The process of HeroService injection looks something like this.

\n
\n \"Service\"\n
\n

Providing serviceslink

\n

You must register at least one provider of any service you are going to use.\nThe provider can be part of the service's own metadata, making that service available everywhere,\nor you can register providers with specific modules or components.\nYou register providers in the metadata of the service (in the @Injectable() decorator),\nor in the @NgModule() or @Component() metadata

\n\n

For more detailed information, see the Dependency Injection section.

\n\n \n
\n\n\n" }