Search code examples
javascriptangulartypescriptangularjs-directiveangular2-services

Angular : use a method from a specific service as useFactory provider for a module


I have a module within my Angular5 app where i m using it like this :

import *....
@NgModule({

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

export class AuthModule {
  constructor( ) {}

}

my problem is that i want to use a custom method: MYMETHOD which i defined in my AuthentificationService

My service is like the following :

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

}

But i seems that i can't find it (AuthentificationService.MYMETHOD )

Suggestions?


Solution

  • try this, it should work using an exported function, add AuthentificationService to deps array

    export function myFactory(authService: AuthentificationService) {
         return () => authService.yourMethod();
    }
    
    providers: [
    AuthentificationService,
    {
      provide: AuthHttp,
      useFactory: myFactory,
      deps: [AuthentificationService, Http, RequestOptions, EnvVarsService, LocalStorageService, RouteNavigator, ReloadTokenEventService],
      multi: true
    }
    ]