尝试添加身份服务,但失败了,该令牌是从API接收的。任何帮助表示赞赏。
app.module:
import { AuthGuard } from './auth-guard.service';
@NgModule({
... providers: [AuthGuard] })
AuthGuardService:
import { JwtHelper } from 'angular2-jwt';
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtHelper: JwtHelper, private router: Router) {
}
canActivate() {
const token = localStorage.getItem('jwt');
if (token && !this.jwtHelper.isTokenExpired(token)) {
return true;
}
this.router.navigate(['login']);
return false;
}
}
AppRouting:
{ path: 'account', component: AccountComponent, canActivate: [AuthGuard] }
错误:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthGuard -> JwtHelper]:
StaticInjectorError(Platform: core)[AuthGuard -> JwtHelper]:
NullInjectorError: No provider for JwtHelper!
Error: StaticInjectorError(AppModule)[AuthGuard -> JwtHelper]:
StaticInjectorError(Platform: core)[AuthGuard -> JwtHelper]:
NullInjectorError: No provider for JwtHelper!
答案 0 :(得分:0)
请删除在构造函数中注入JwtHelper并在canActivate内部为JwtHelper创建一个对象,如下所示:
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate() {
let jwtHelper: JwtHelper = new JwtHelper();
const token = localStorage.getItem('jwt');
if (token && !this.jwtHelper.isTokenExpired(token)) {
return true;
}
this.router.navigate(['login']);
return false;
}
}