18

我需要从静态方法内部访问我的自定义 http 服务,例如:

import {Control} from 'angular2/common';
import {HttpService} from './http.service';

class UsernameValidator {
    static usernameExist(control: Control): Promise<ValidationResult> { 
        ... /* Access my HTTPservice here */
    }
}

在这种情况下如何访问服务?

4

3 回答 3

10

另一种方法是返回一个函数。这样,此函数可以访问HttpService创建期间提供的实例:

class UsernameValidator {
  static createUsernameExist(http:HttpService) {
    return (control: Control) => { 
      ... /* Access my HTTPservice here */
    }
  }
}

然后你可以像这样使用它:

validator: UsernameValidator.createUsernameExist(this.httpService)
于 2016-02-19T13:08:28.503 回答
3
class UsernameValidator {
    constructor(http:HttpService){}

    usernameExist(control: Control): Promise<ValidationResult> { 
        ... /* Access my HTTPservice here */
    }
}

然后像使用它

validator: new UsernameValidator(http).usernameExist

需要将HttpService其注入到组件构造函数中,然后传递给手动创建的验证器实例,如上所示。

于 2016-02-19T12:53:45.307 回答
1

使用Günter Zöchbauer 的回答,这就是我实现验证器以从AsyncValidatorFn...内部访问服务的方式

IMHO it seems cleaner to let the DI inject the service dependencies directly into the validator class instead of passing the dependencies to a static method from the consumer component to create the AsyncValidatorFn.

Create your injectable validator class

import { Injectable } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';

@Injectable
export class UsernameValidator {
  constructor(
    private http: HttpService,
  ) { }

  usernameExists: AsyncValidatorFn = (control: AbstractControl): Observable<ValidationErrors> => {
    // access your HttpService here...
  }
}

Provide validator for injection in your module declaration

@NgModule({
  providers: [
    UsernameValidator, // register your validator for injection
  ],
})
export class UserModule { }

Set validator function in your component form

constructor(
  private formBuilder: FormBuilder,
  private usernameValidator: UsernameValidator, // inject your validator
) { }

ngOnInit() {
  this.form = this.formBuilder.group({
    username: [
      null, // initial value
      [Validators.required], // sync validators
      [this.usernameValidator.usernameExists], // async validators
    ],
  });
}
于 2018-10-12T15:43:51.933 回答