在 Jwthelperservice 中出错



我对角度很陌生,我获取了代码:

网址 = https://github.com/DavideViolante/Angular-Full-Stack

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)

您必须将 AuthGuard 添加到 app.module 中的提供程序列表中:

  providers: [
    AuthGuard
  ],

出现此错误只是因为您尚未在应用程序模块文件中添加 jwtmodule。所以在这里你需要添加它的配置,所以,请将以下代码添加到你的app.module.ts文件中:

import { JwtHelperService, JwtModule } from '@auth0/angular-jwt';
...
@NgModule({
imports: [
     ...
    JwtModule.forRoot({
    config: {
      tokenGetter: function  tokenGetter() { 
      return localStorage.getItem('token');
      } 
   }
 });
 ...
 ],
 ...
 })

相关内容

  • 没有找到相关文章

最新更新