跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

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:

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

Using importProvidersFrom() in component providers ​

The importProvidersFrom() function also returns EnvironmentProviders:

ts
@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:

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

For route-specific providers ​

Use the providers array in route configurations:

ts
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:

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

基于 MIT 许可证发布。