Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}
    ]);
  }
}
like image 813
Codehan25 Avatar asked Mar 07 '19 08:03

Codehan25


People also ask

What does @inject do in Angular?

@Inject() is a manual mechanism for letting Angular know that a parameter must be injected. Injecting ChatWidget component to make the component behave like a singleton service so that the component state remain same across the app.

How many ways we can inject service in Angular?

There are three types of Dependency Injections in Angular, they are as follows: Constructor injection: Here, it provides the dependencies through a class constructor. Setter injection: The client uses a setter method into which the injector injects the dependency.


2 Answers

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]
  }
}),
like image 105
smnbbrv Avatar answered Nov 03 '22 00:11

smnbbrv


Additional to this solution, you can also make use of the Angular's Injector API.

Follow the docs here

like image 25
Kushagra Saxena Avatar answered Nov 03 '22 00:11

Kushagra Saxena