错误:没有JwtHelper的提供者
问题描述:
我是Angular2的新手,我使用jwthelper编码jwt令牌并提取详细信息。错误:没有JwtHelper的提供者
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);
}
}
找不到以下错误的解决方案,并告诉我这里有什么不正确。
ERROR Error: No provider for JwtHelper!
答
这是因为您试图在组件/服务的构造函数中注入JwtHelper
。这仅适用于供应商的。
根据using jwthelper in components部分,您必须创建一个新对象并使用它。
在服务,
constructor(){} //remove from constructor.
getUser(){
let jwtHelper: JwtHelper = new JwtHelper();
var token = JSON.parse(localStorage.getItem('currentUser'));
return this.jwtHelper.decodeToken(token.token);
}
这是在服务中使用jwthelper的最有效的方法是什么? – Harshakj89
检查[这里](https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts#L207)它只是一个没有任何装饰器的导出类。 –
现在我明白了。 – Harshakj89