如何将一个服务注入到另一个服务中,并在 Angular 中的导出常量或接口中使用它?

How to inject a service into another service and use it within exported constants or interfaces in Angular?

我想将一个服务注入另一个服务,我想用它来翻译导出常量中的字符串。

我的代码目前看起来像这样(我在这里进行了简化)

// 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),
];

但是,我收到此错误,因为在组件外部未检测到注入的服务:

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

这个问题最干净的解决方案是什么?

您可以简单地在服务中创建一个 getSeries 方法,它将 return 常量的值。 This 将在 MyService class 中定义,因此没有错误。

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

您必须调用 getSeries() 方法而不是 ALL_SERIES