【问题标题】:Error when adding AuthGuard Service into Component for angular将 AuthGuard 服务添加到 Angular 组件时出错
【发布时间】: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 必须在导入组件的rootmodule.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


【解决方案1】:

请删除在构造函数中注入 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;
  }
}

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2020-02-20
    相关资源
    最近更新 更多