错误错误:没有JwtHelper的提供者

Har*_*nna 3 authentication jwt web angular

我是Angular2的新手,我正在使用jwthelper来编码jwt令牌并提取细节.

import { Injectable } from '@angular/core';

import { JwtHelper } from 'angular2-jwt';

@Injectable()
export class SessionService {

  constructor(private jwtHelper: JwtHelper){}

  getUser(){
    var token = JSON.parse(localStorage.getItem('currentUser'));
    return this.jwtHelper.decodeToken(token.token);
  }
}
Run Code Online (Sandbox Code Playgroud)

找不到以下错误的解决方案,并告诉我这里有什么不对.

错误错误:没有JwtHelper的提供者!

Sur*_*Rao 11

这是因为您尝试注入JwtHelper组件/服务的构造函数.这仅适用于提供商.

根据组件部分中使用jwthelper,您必须创建一个新对象并使用它.

在您的服务中,

constructor(){} //remove from constructor.

  getUser(){
    let jwtHelper: JwtHelper = new JwtHelper();
    var token = JSON.parse(localStorage.getItem('currentUser'));
    return this.jwtHelper.decodeToken(token.token);
  }
Run Code Online (Sandbox Code Playgroud)