How to inject a service into custom .ts file in Angular 2+

时间:2019-04-08 12:24:05

标签: angular

I have a form.constants.ts file:

const FORM: Array<IForm> = [
  {
    type: EInputType.DatePicker,
    label: 'DATE_FROM',
    formControlName: 'startDate',
    placeholder: 'ENTER_DATE_FROM',
    value: null
  }
]

also I have a global.helper.service, and into it have a method that get query params from url:

  public getQueryParam () {
    this.activatedRoute.queryParams.subscribe(params => {
      const userId = params['id'];
      console.log(userId);
    });
  }

So I need to inject my service global.helper.service into my form.constants.ts for using getQueryParam method in the form.constants.ts.

1 个答案:

答案 0 :(得分:1)

Angular doc中所述,您不能在/** * @param string|null $firstname */ public function setFirstname(?string $firstname): self { $this->firstname = $firstname; return $this } 之外的其他地方(例如,组件)注入服务。

enter image description here

因此,您需要一个Class和一个Class才能向其中注入Angular服务。

您还可以参考文档的the DI part