Error Encyclopedia

EnvironmentProviders in wrong context

This error occurs when EnvironmentProviders are used in a context that only accepts regular providers, such as a component's providers array. Environment providers are designed for application-wide configuration and can only be used in environment injectors (like the root injector configured in bootstrapApplication or route configurations).

Common scenarios

Using provideHttpClient() in component providers

Functions like provideHttpClient() return EnvironmentProviders, which cannot be used at the component level:

@Component({  providers: [    provideHttpClient(), // ERROR: EnvironmentProviders can't be used here  ],})export class UserProfile {}

Using importProvidersFrom() in component providers

The importProvidersFrom() function also returns EnvironmentProviders:

@Component({  providers: [    importProvidersFrom(SomeModule), // ERROR: can't be used for component providers  ],})export class DataView {}

Debugging the error

Move the environment providers to an appropriate location:

For application-wide providers

Configure environment providers in bootstrapApplication:

bootstrapApplication(App, {  providers: [provideHttpClient(), importProvidersFrom(SomeModule)],});

For route-specific providers

Use the providers array in route configurations:

const routes: Routes = [  {    path: 'admin',    component: AdminView,    providers: [provideHttpClient(withInterceptors([authInterceptor]))],  },];

For component-level services

If you need component-scoped services, use regular providers instead of environment providers:

@Component({  providers: [    UserClient, // Regular provider - this works    {provide: API_URL, useValue: '/api'}, // Value provider - this works  ],})export class UserProfile {}

The error message specifies which provider caused the issue. Check that all items in your component's providers array are regular providers, not environment providers returned by functions like provideHttpClient(), provideRouter(), or importProvidersFrom().