Codehan25
Codehan25

Reputation: 3014

Inject an Angular service into an exported function?

I have the following exported function (out of class) that is defined in my AppComponent:

export function multiTranslateHttpLoaderFactory(http: HttpClient) {
  return new MultiTranslateHttpLoader(http, [
    {prefix: './assets/i18n/default/', suffix: '.json'},
    {prefix: './assets/i18n/bc/', suffix: '.json'}
  ]);
}

This is then used within the import arrays in the AppModule in this way:

TranslateModule.forRoot ({
  loader: {
    provide: TranslateLoader,
    useFactory: multiTranslateHttpLoaderFactory,
    deps: [HttpClient]
  }
}),

I would need a way to use my AuthService within the exported function, since I need certain properties to implement logic.

Is there a possibility for that?

For example, I would like to use my authService in this way:

export function multiTranslateHttpLoaderFactory(http: HttpClient) {
  let bc = this.authService.activeBusinessCase$.getValue();
  if(bc){
    ...
  }else{
    return new MultiTranslateHttpLoader(http, [
      {prefix: './assets/i18n/default/', suffix: '.json'},
      {prefix: './assets/i18n/bc/', suffix: '.json'}
    ]);
  }
}

Upvotes: 10

Views: 18771

Answers (1)

smnbbrv
smnbbrv

Reputation: 24541

Nothing easier.

export function multiTranslateHttpLoaderFactory(http: HttpClient, auth: AuthService) {
  // add AuthService logic

  return new MultiTranslateHttpLoader(http, [
    {prefix: './assets/i18n/default/', suffix: '.json'},
    {prefix: './assets/i18n/bc/', suffix: '.json'}
  ]);
}

and pass it as dependency

TranslateModule.forRoot ({
  loader: {
    provide: TranslateLoader,
    useFactory: multiTranslateHttpLoaderFactory,
    deps: [HttpClient, AuthService]
  }
}),

Upvotes: 16

Related Questions