这个错误通常发生在Angular中使用函数式守卫时,没有正确提供必要的依赖项。解决方法是确保在模块的providers数组中正确提供所需的依赖项。
以下是一个解决该错误的示例:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class MyGuard implements CanActivate {
constructor(private myService: MyService) {} // 假设守卫依赖MyService服务
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
// 守卫逻辑
return true;
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MyGuard } from './my-guard';
import { MyService } from './my-service';
const routes: Routes = [
{ path: 'example', component: ExampleComponent, canActivate: [MyGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [MyGuard, MyService], // 确保在这里提供守卫和服务
exports: [RouterModule]
})
export class AppRoutingModule { }
通过以上步骤,你已经正确提供了守卫和守卫所依赖的服务,应该不再出现"NullInjectorError: NullInjectorError: 未提供者"错误。