Angular创建复用Toolbar组件遇NullInjectorError:无MatSidenavContainer提供者
问题根源分析
你遇到的NullInjectorError: No provider for MatSidenavContainer!错误,主要由两个核心问题导致:
- AppModule中RouterModule的导入格式错误,引发模块加载异常
- AuthenticationService未正确注册为可注入服务
具体修复步骤
1. 修复RouterModule的导入格式
在app.module.ts的imports数组中,你错误地将RouterModule.forRoot(routes)包裹在了额外数组里,这会导致Angular无法正确识别并加载该模块。修改如下:
修改后的app.module.ts imports部分
imports: [ BrowserModule, BrowserAnimationsModule, AngularMaterialModule, HttpClientModule, RouterModule.forRoot(routes) // 移除外层的[] ],
2. 注册AuthenticationService
你的ToolbarComponent依赖AuthenticationService,但该服务未在AppModule中声明为可注入提供者,有两种解决方式:
方式一:在AppModule的providers中添加服务
providers: [ AuthGuard, AuthenticationService // 添加这一行注册服务 // ...其他提供者 ],
方式二:在服务类中使用providedIn: 'root'(推荐)
直接修改AuthenticationService的定义,让Angular自动全局注册该服务:
@Injectable({ providedIn: 'root' // 添加这一行 }) export class AuthenticationService { // ...服务原有代码 }
3. 优化组件结构(可选但推荐)
当前ToolbarComponent中包含mat-sidenav-container,不符合组件职责单一原则。建议将mat-sidenav-container移到AppComponent模板中,让Toolbar仅负责导航栏逻辑:
app.component.html
<app-toolbar (toggleSidenav)="sidenav.toggle()"></app-toolbar> <mat-sidenav-container> <mat-sidenav #sidenav> <mat-nav-list> <a mat-list-item [routerLink]="'/feed'"><mat-icon>home</mat-icon>Feed</a> <a mat-list-item [routerLink]="['/profile', getProfile()]"><mat-icon>person_outline</mat-icon>Profile</a> <a mat-list-item (click)="authService.logout()" [routerLink]="'/login'" *ngIf="authService.isUserLoggedIn()"><mat-icon>exit_to_app</mat-icon>Logout</a> <a mat-list-item (click)="sidenav.toggle()"> Close</a> </mat-nav-list> </mat-sidenav> <mat-sidenav-content> <router-outlet></router-outlet> </mat-sidenav-content> </mat-sidenav-container>
修改后的toolbar.component.html
<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button (click)="onToggleSidenav()"> <mat-icon>menu</mat-icon> </button> <h1>Twitter</h1> </mat-toolbar-row> <mat-toolbar-row> <img class="twitter" src="assets/twitter.png" alt=""> </mat-toolbar-row> </mat-toolbar>
修改后的toolbar.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { AuthenticationService } from '../security-login/authentication.service'; @Component({ selector: 'app-toolbar', templateUrl: './toolbar.component.html', styleUrls: ['./toolbar.component.css'] }) export class ToolbarComponent implements OnInit { @Output() toggleSidenav = new EventEmitter<void>(); constructor(public authService: AuthenticationService) { } ngOnInit(): void { } onToggleSidenav() { this.toggleSidenav.emit(); } getProfile() { const id = sessionStorage.getItem('userId'); return id; } }
验证修复
完成上述修改后,重新启动应用,使用<app-toolbar>调用组件时,错误即可消除。
内容的提问来源于stack exchange,提问作者Ruschisb
相关产品推荐
相关产品推荐

