在Angular 2+中的模块声明中从导出函数访问服务

时间:2017-09-05 12:06:40

标签: angular typescript service injectable

我有以下模块声明:

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 { }

和服务:

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

@Injectable()
export class ConnectionService {
    id;

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

我需要在模块导出函数的tokenGetter中使用Services方法“getToken”,但我无法使其工作且Google没有回答我的问题(或者我无法正常查看)

1 个答案:

答案 0 :(得分:1)

你可以尝试这样吗

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