NullInjectorError: MatSnackBar无提供者——通用服务注入失败求助
If injecting MatSnackBar directly into components works but fails in a service, here are the key fixes to resolve the issue:
1. Import MatSnackBarModule in Your Module
Your service needs access to the providers exposed by MatSnackBarModule. Add it to the imports array of the module where your service is declared (e.g., AppModule or a feature module):
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MatSnackBarModule } from '@angular/material/snack-bar'; // Import the module import { SnackBarService } from './snack-bar.service'; import { AppComponent } from './app.component'; @NgModule({ imports: [BrowserModule, MatSnackBarModule], // Include MatSnackBarModule here declarations: [AppComponent], providers: [SnackBarService], // Declare your service as a provider bootstrap: [AppComponent] }) export class AppModule { }
2. Use Root-Level Provider for Your Service
Ensure your service is provided at the root level so Angular can resolve the MatSnackBar dependency correctly. Add providedIn: 'root' to your service's @Injectable decorator:
import { Injectable } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root' // Makes the service a singleton accessible app-wide }) export class SnackBarService { constructor(private snackBar: MatSnackBar) { } showMessage(message: string, action = 'Close') { this.snackBar.open(message, action, { duration: 3000, horizontalPosition: 'center' }); } }
3. Avoid Circular Dependencies
Check if your service is injected into a component that's also referenced by the service. Circular dependencies can break dependency resolution. Refactor your code to remove any circular references if present.
Why Component Injection Works
When you inject MatSnackBar directly into a component, the component belongs to a module that already imports MatSnackBarModule, so the dependency is resolved automatically. Services, however, need their declaring module to include the required material module to access the provider.
内容的提问来源于stack exchange,提问作者Shyam Shinde

