0

I would like to inject a service into another service with which I want to translate strings within exported constants.

My code currently looks like this (I've simplified it here)

// Imports..

@Injectable(
  { providedIn: 'root' }
)
export class MyService {

  constructor(private httpClient: HttpClient, private injectedService: InjectedService) {
  }

  // Methods..
}

export enum Series {
  prop_1 = 'String_1',
  prop_2 = 'String_2',
  prop_3 = 'String_3',
}

export const ALL_SERIES: Series[] = [
  this.injectedService.translate(Series.prop_1),
  this.injectedService.translate(Series.prop_1),
  this.injectedService.translate(Series.prop_1),
];

However, I get this error because the injected service is not detected outside the component:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'injectedService' of undefined

What would be the cleanest solution to this problem?

Codehan25
  • 2,704
  • 10
  • 47
  • 94
  • the type for injectedService is not mentioned in the constructor the way it is mentioned for httpClient, if the type for injectedService will be mentioned then angular would know what type to use for DI – manishgdev Dec 11 '19 at 12:54
  • @manishgdev I'm sorry, I forgot it in my simplified version. Still does not work.. – Codehan25 Dec 11 '19 at 12:56
  • doesn't makes sense to inject a service inside another service if you want to use it outside the service........................ – Pedro Bezanilla Dec 11 '19 at 12:58
  • @PedroB. That's exactly my question. How could I proceed here? – Codehan25 Dec 11 '19 at 13:02
  • may be this would help https://stackoverflow.com/questions/51131894/angular-inject-service-into-service-no-provider – manishgdev Dec 11 '19 at 13:21

1 Answers1

2

You could simply create a getSeries method in the service that will return the values of the constant. This will be defined inside the MyService class and thus no error.

@Injectable({
  providedIn: 'root'
})
export class MyService {

  constructor(private httpClient: HttpClient, private injectedService: InjectedService) {}

  // Methods..

  getSeries(): Series[] {
    return [
      this.injectedService.translate(Series.prop_1),
      this.injectedService.translate(Series.prop_1),
      this.injectedService.translate(Series.prop_1),
    ];
  }
}

export enum Series {
  prop_1 = 'String_1',
    prop_2 = 'String_2',
    prop_3 = 'String_3',
}

Instead of ALL_SERIES you would have to call getSeries() method though.

abd995
  • 1,649
  • 6
  • 13