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
