2017-06-21 138 views
2

我是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!

回答

6

這是因爲您試圖在組件/服務的構造函數中注入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); 
    } 
+0

這是在服務中使用jwthelper的最有效的方法是什麼? – Harshakj89

+1

檢查[這裏](https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts#L207)它只是一個沒有任何裝飾器的導出類。 –

+0

現在我明白了。 – Harshakj89

相關問題