2017-06-21 13 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

関連する問題