简体   繁体   English

将AuthGuard服务添加到Angular组件时出错

[英]Error when adding AuthGuard Service into Component for angular

Trying to add an identity service but it's falling over, the token is received from the API. 尝试添加身份服务但失败了,该令牌是从API接收到的。 Any help appreciated. 任何帮助表示赞赏。

app.module: app.module:

import { AuthGuard } from './auth-guard.service';

@NgModule({
...  providers: [AuthGuard] })

AuthGuardService: 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: AppRouting:

{ path: 'account', component: AccountComponent, canActivate: [AuthGuard] }

Error: 错误:

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!

Please remove injecting JwtHelper in a constructor and create an object for JwtHelper inside of your canActivate like this: 请删除在构造函数中注入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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM