我对角度很新,我拿了代码:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';
import { UserService } from './user.service';
import { HttpClient } from '@angular/common/http';
import { User } from '../shared/models/user.model';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
loggedIn = false;
isAdmin = false;
currentUser: User = new User();
constructor(private userService: UserService,
private http: HttpClient,
private router: Router,
private jwtHelper: JwtHelperService) {
const token = localStorage.getItem('token');
if (token) {
const decodedUser = this.decodeUserFromToken(token);
this.setCurrentUser(decodedUser);
}
}
login(emailAndPassword) {
return this.userService.login(emailAndPassword).map(
res => {
localStorage.setItem('token', res.token);
const decodedUser = this.decodeUserFromToken(res.token);
this.setCurrentUser(decodedUser);
return this.loggedIn;
}
);
}
decodeUserFromToken(token) {
return this.jwtHelper.decodeToken(token).user;
}
}
我正在使用Visual Studio代码,并没有抛出任何语法错误。
但在控制台中收到错误:
Error: StaticInjectorError(AppModule)[AuthService -> JwtHelperService]:
StaticInjectorError(Platform: core)[AuthService -> JwtHelperService]:
NullInjectorError: No provider for JwtHelperService!
at _NullInjector.get (core.js:994)
at resolveToken (core.js:1292)
at tryResolveToken (core.js:1234)
at StaticInjector.get (core.js:1102)
at resolveToken (core.js:1292)
at tryResolveToken (core.js:1234)
答案 0 :(得分:0)
您必须将AuthGuard添加到app.module中的提供者列表中:
providers: [
AuthGuard
],
答案 1 :(得分:0)
此错误即将到来只是因为您尚未在应用程序模块文件中添加jwtmodule。因此,在这里您需要添加它的配置,因此,请将以下代码添加到您的app.module.ts文件中:
import { JwtHelperService, JwtModule } from '@auth0/angular-jwt';
...
@NgModule({
imports: [
...
JwtModule.forRoot({
config: {
tokenGetter: function tokenGetter() {
return localStorage.getItem('token');
}
}
});
...
],
...
})