liveBook · Manning

Providers array

As explained in Modern Angular

A providers array is Angular metadata that lists dependency-injection providers for an NgModule, component, or application configuration.

A providers array tells Angular which values to inject for dependency-injection tokens. Older Angular applications commonly placed providers in NgModules or components, while standalone applications also configure them at application and route boundaries. section 2.3.2 section 2.4.4

Use the array at the scope where a dependency should be available:

  • Component providers make a service available to that component and its relevant descendants; a standalone LoginComponent can provide AuthService directly. section 2.3.1 section 2.3.2
  • Application providers configure dependencies globally in the standalone application configuration, using existing standalone APIs or importProvidersFrom for NgModule providers. section 2.3.2
  • Route providers limit a service to a lazy-loaded route tree, supporting isolated service instances and deferred route-specific state or requests. section 2.4.4

Login and employee services

A standalone LoginComponent can list AuthService in its providers array and inject HttpClient through that service. An employees route can instead list EmployeeService in its providers array, keeping that instance available only within the employee routes. section 2.3.1 section 2.4.4

Listing 2.17 Adding providers to a lazy-loaded route
{ 
    path: 'employees', 
    providers: [EmployeeService],
    loadChildren: () => {
        return import('./pages/employees/employees.routes').then(
            (m) => m.routes,
        );
    },
},

Inspect a route definition that scopes EmployeeService to the lazy-loaded employees route. section 2.4.4

How Modern Angular covers it

How deep it goes
Explains token-to-value injection, component/application/route scopes, and NgModule interoperability; stops short of deeper DI internals.
Examples
Uses LoginComponent with AuthService and EmployeeService scoped to a lazy-loaded employees route.
What it assumes
Assumes Angular dependency injection and NgModules, while defining providers through concrete standalone and routing examples.
What you can do after
Operate/configure standalone applications with component, application, and route providers, including dependencies retained in NgModules.
How it connects
Connects dependency injection with NgModules, standalone components, routes, lazy loading, HttpClient, and importProvidersFrom.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.