10

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'}
    ]);
  }
}
4
  • Why not add it to the deps list and the factory parameter list, then?
    – jonrsharpe
    Commented Mar 7, 2019 at 8:31
  • Hmm, I don't get it..
    – Codehan25
    Commented Mar 7, 2019 at 8:33
  • 1
    Well, you see how you're injecting the HttpClient into it? Just do that again with the service.
    – jonrsharpe
    Commented Mar 7, 2019 at 8:34
  • Additional to this solution, you can also make use of the Angular's Injector API. Follow the docs here Commented Mar 8, 2019 at 6:09

1 Answer 1

16

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]
  }
}),
2
  • Seems to work. But I do not need to write my function back inside the AppModule right? Because I would like to keep it in the AppComponent, so my AppModule is clean.
    – Codehan25
    Commented Mar 7, 2019 at 8:37
  • 1
    ehm. The function location is all up to you. Nobody restricts you in that
    – smnbbrv
    Commented Mar 7, 2019 at 8:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.