Angular:使用特定服务中的方法作为模块的useFactory提供程序

时间:2018-04-03 16:35:09

标签: javascript angular typescript angularjs-directive angular2-services

我的 Angular5 应用中有一个模块,我在这里使用它:

import *....
@NgModule({

  providers: [
    AuthentificationService,
    {
      provide: AuthHttp,
      useFactory: AuthentificationService.MYMETHOD,
      deps: [Http, RequestOptions, EnvVarsService, LocalStorageService, RouteNavigator, ReloadTokenEventService]
    }
  ]
})

export class AuthModule {
  constructor( ) {}

}

我的问题是我想使用自定义方法:我在 AuthentificationService

中定义的MYMETHOD

我的服务如下:

@Injectable()
export class AuthentificationService {

  constructor() {}

  public authHttpServiceFactory(http: Http, options: RequestOptions,
                                envVarsService: EnvVarsService,
                                localStorageService: LocalStorageService,
                                router: RouteNavigator,
                                reloadTokenEventService: ReloadTokenEventService) {

    return new AuthHttp(new AuthConfig({
      tokenName: 'X-Auth-Token',
      headerName: 'X-Auth-Token',
      noTokenScheme: true,
      noJwtError: true,
      tokenGetter: (() => this.getAccessToken(http, options, envVarsService, localStorageService, router, reloadTokenEventService)),
      globalHeaders: [{'Content-Type': 'application/json'}],
    }), http, options);
  }


  private getAccessToken(): Promise<string> {
         // SOME TREATMENT
    }
  }

}

但我似乎找不到它(AuthentificationService.MYMETHOD)

建议吗

1 个答案:

答案 0 :(得分:0)

试试这个,它应该使用导出的函数,将AuthentificationService添加到deps数组

export function myFactory(authService: AuthentificationService) {
     return () => authService.yourMethod();
}

providers: [
AuthentificationService,
{
  provide: AuthHttp,
  useFactory: myFactory,
  deps: [AuthentificationService, Http, RequestOptions, EnvVarsService, LocalStorageService, RouteNavigator, ReloadTokenEventService],
  multi: true
}
]