0

Trying to add an identity service but it's falling over, the token is received from the API. Any help appreciated.

app.module:

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

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

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:

{ 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!
Zoe
  • 27,060
  • 21
  • 118
  • 148
davidgray
  • 1
  • 2
  • `JwtHelper` must be provided in `root` or `module.ts` in which the component is imported – Nickolaus Jan 18 '19 at 17:56
  • What version of Angular are you using? angular2-jwt has a peer dependency of @angular/http ^2.0.0 || ^4.0.0 – night_owl Jan 18 '19 at 18:00
  • @davidgray follow this answer (https://stackoverflow.com/questions/52378120/angular-6-using-angular2-jwt) – Abhishek Jan 18 '19 at 18:04
  • @davidgray seems you need to use a new version https://github.com/auth0/angular2-jwt and import `JwtHelperService` – Samuel Ayvazyan Jan 18 '19 at 23:59
  • Thanks all. I am using angular6, I've removed the use of JwT and added the canActivate function to just return true. Problem still exists tho... something to do with the way I have CanActivate added :( – davidgray Jan 19 '19 at 00:12
  • Found the answer in the end was related to the items I was sending through to the constructor, once removed the code worked! Thanks all for the help – davidgray Jan 21 '19 at 03:29

1 Answers1

0

Please remove injecting JwtHelper in a constructor and create an object for JwtHelper inside of your canActivate like this:

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;
  }
}