简体   繁体   English

如何在Angular 6导出功能中使用依赖注入

[英]How to use Dependency Injection in Angular 6 export function

I have tried this 我已经试过了

export function uniqueUserNameValidation(commonsService: CommonsService): AsyncValidatorFn {
  return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
    return commonsService.uniqueUserName(c.value).pipe(
      map(data => {
        return data && data.status ? {
          'uniqueValidation': true
        } : null
      })
    )
  }
}

Common Services Method 共同服务方法

uniqueUserName(name:string){
        return this.http.get<booleanData>(constDefault.API_URL+"/commons/nameAlreadyExist/"+name+"/Tank")
}

I am getting this error 我收到此错误

core.js:1673 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'uniqueUserName' of undefined TypeError: Cannot read property 'uniqueUserName' of undefined core.js:1673错误错误:未捕获(承诺):TypeError:无法读取未定义的属性'uniqueUserName'TypeError:无法读取未定义的属性'uniqueUserName'

Angular's automatic dependency injection only works for angular component constructors (which are being managed by the DI system). Angular的自动依赖项注入仅适用于角度组件构造函数(由DI系统管理)。

As a solution to the specific problem shown in the question, you can inject the service into the component which will be calling the uniqueUserNameValidation and then pass the service as an argument to uniqueUserNameValidation . 为了解决问题中显示的特定问题,您可以将服务注入到将要调用uniqueUserNameValidation的组件中,然后将该服务作为参数传递给uniqueUserNameValidation I think that, in general, this would be the preferred solution to your problem because it doesn't stray from standard angular practices. 我认为,总的来说,这将是解决您问题的首选方法,因为它不会偏离标准的角度做法。

Example

export class MyComponent {
  constructor(private commonsService: CommonsService, private fb: FormBuilder) {}

  ngOnInit() {
    const form = this.fb.group({
      name: ['', uniqueUserNameValidation(this.commonsService)]
    })
  }
}

I assume that your CommonsService is a proper Angular Service. 我假设您的CommonsService是适当的Angular服务。 If so, you could use Injector . 如果是这样,您可以使用Injector

First import and declare the Injector in your module (app.module.ts etc.) and in the constructor of module init the instance: 首先,在模块(app.module.ts等)中以及实例实例的模块构造函数中导入并声明Injector

import {Injector} from '@angular/core';

export let InjectorInstance: Injector;

...
...
...


export class AppModule {

  constructor(private injector: Injector) {
    InjectorInstance = this.injector;
  }
}

Then in your file that is exporting the function, import the variable from the module: 然后在导出函数的文件中,从模块导入变量:

import {InjectorInstance} from 'path/to/app.module';

Then you can use the .get() method of Injector to get the service instance: 然后,可以使用Injector.get()方法获取服务实例:

export function uniqueUserNameValidation(): AsyncValidatorFn {

  const commonsService = InjectorInstance.get<CommonsService>(CommonsService);

  return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
    return commonsService.uniqueUserName(c.value).pipe(
      map(data => {
        return data && data.status ? {
          'uniqueValidation': true
        } : null
     })
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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