PHP技术那点事
全部
技术
PHP
MySQL
前端
Linux
JAVA
退出
编辑文章
选择分类
PHP
MySQL
前端
Linux
Java
工具
选择专栏
设计模式
java基础
Angular学习
Java面试题
描述:
封面图上传 :
+
点击上传图片
使用Angular8的路由守卫功能报错,具体如下: ``` core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[LoginGuard]: StaticInjectorError(Platform: core)[LoginGuard]: NullInjectorError: No provider for LoginGuard! NullInjectorError: StaticInjectorError(AppModule)[LoginGuard]: StaticInjectorError(Platform: core)[LoginGuard]: NullInjectorError: No provider for LoginGuard! at NullInjector.get (core.js:855) at resolveToken (core.js:17514) at tryResolveToken (core.js:17440) at StaticInjector.get (core.js:17266) at resolveToken (core.js:17514) at tryResolveToken (core.js:17440) at StaticInjector.get (core.js:17266) at resolveNgModuleDep (core.js:30393) at NgModuleRef_.get (core.js:31578) at resolveNgModuleDep (core.js:30393) at resolvePromise (zone-evergreen.js:797) at resolvePromise (zone-evergreen.js:754) at zone-evergreen.js:858 at ZoneDelegate.invokeTask (zone-evergreen.js:391) at Object.onInvokeTask (core.js:39680) at ZoneDelegate.invokeTask (zone-evergreen.js:390) at Zone.runTask (zone-evergreen.js:168) at drainMicroTaskQueue (zone-evergreen.js:559) ``` admin-routing.module 具体代码 : ``` import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { IndexComponent } from '../admin/index/index.component'; import { AdminComponent } from './admin.component'; import { LoginGuard } from '../common-share/guard/login.guard'; const routes: Routes = [ { path: '', component: AdminComponent, children: [ { path: '', redirectTo: 'index', pathMatch: 'full' }, { path: 'index', component: IndexComponent, canActivate: [LoginGuard] }, ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class AdminRoutingModule { } ``` 路由守卫代码: ``` import {ActivatedRoute, CanActivate, Router} from '@angular/router'; import { AuthService } from '../api/auth/auth.service'; import { Injectable } from '@angular/core'; /** * 检查登录 */ @Injectable() export class LoginGuard implements CanActivate{ constructor(private auth: AuthService,private router: Router, private route: ActivatedRoute) { } canActivate(){ //检查登录 if(!this.auth.checkHasLogin()){ this.router.navigate(['/login'], { relativeTo: this.route }); }; return true; } } ``` 具体是说我这个LoginGuard没有注入,然后找不到这个守卫 #####网上解决办法: - 导入HttpClientModule ``import { HttpClientModule } from '@angular/common/http';`` 检查发现我已经导入了,所以不可能是这个问题 --- 后面检查才发现是,我确实没有注入,我没有在admin-routing.module 里面把LoginGuard加入providers里面,导致找不到。 #####具体解决办法,在admin-routing.module providers里面加入LoginGuard ``` @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], providers: [LoginGuard] }) ```
保存文章