简体   繁体   中英

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

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 .

As explained in the Angular doc , you can't inject a service somewhere else than a Class (eg: a Component).

在此处输入图片说明

So you'll need a Class with a constructor to inject an Angular Service into it.

You can also refer to the DI part of the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM