【发布时间】:2019-01-18 17:54:00
【问题描述】:
尝试添加身份服务但失败了,从 API 接收到令牌。任何帮助表示赞赏。
app.module:
import { AuthGuard } from './auth-guard.service';
@NgModule({
... providers: [AuthGuard] })
AuthGuard服务:
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;
}
}
应用路由:
{ 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!
【问题讨论】:
-
JwtHelper必须在导入组件的root或module.ts中提供 -
您使用的是哪个版本的 Angular? angular2-jwt 的对等依赖关系为 @angular/http ^2.0.0 || ^4.0.0
-
@davidgray 关注这个答案 (stackoverflow.com/questions/52378120/…)
-
@davidgray 看来您需要使用新版本 github.com/auth0/angular2-jwt 并导入
JwtHelperService -
谢谢大家。我正在使用 angular6,我删除了 JwT 的使用并添加了 canActivate 函数以返回 true。问题仍然存在...与我添加 CanActivate 的方式有关:(
标签: javascript angular identity