5

I have the following Module declaration:

import { ConnectionService } from './services/connection.service';
import { NgModule } from '@angular/core';
import { Http, RequestOptions } from '@angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
    tokenGetter: (() => sessionStorage.getItem('token'))
  }), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ],
})

export class AuthModule { }

and Service:

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

@Injectable()
export class ConnectionService {
    id;

    getToken() {
        return JSON.parse(sessionStorage.getItem('token'))[this.id];
    }
}

I need to use the Services method "getToken" in the tokenGetter on the Modules exported function, but I can't make it work and Google hasn't answered my question (or I haven't been able to look properly).

1 Answer 1

1

Hi can you try like this

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
       tokenName: 'token',
       tokenGetter: (() => new ConnectionService().getToken())
       }), http, options);
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you but it didn't work for me. In the end I made it the other way around and defined the "AuthHttp" object directly inside the service.
I couldn't try it. On the real project I have a constructor in the service to access Http and other stuff, so it didn't let me. But in any case I think adding the object to the service instead of the other way around is a better approach, at least in my case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.