将自定义服务注入自定义验证器

Inject custom service into a custom Validator

我正在尝试制作自定义 Angular 2 表单 Validator 以检查数据库中是否存在用户。

这是我自定义表单的代码Validator

import { FormControl } from '@angular/forms';
import {API} from "../services/api";
import {ReflectiveInjector} from "@angular/core";

export class EmailValidator {

  constructor() {}

  static checkEmail(control: FormControl,): any {
    let injector = ReflectiveInjector.resolveAndCreate([API]);
    let api = injector.get(API);

    return api.checkUser(control.value).then(response => {
      response;
    });

  }

}

这是我的自定义服务,负责向后端 api 上的节点

发出请求
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class API {
  private backendUrl = 'http://127.0.0.1:5000/api/register/';

  constructor(private http: Http) { }

  checkUser(email:string): Promise<any> {
    return this.http.get(this.backendUrl + email)
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  }

当我尝试验证用户时,这是显示的错误

EXCEPTION: Error in ./TextInput class TextInput - inline template:0:0 caused by: No provider for Http! (API -> Http)

我做错了什么?

谢谢

@Injectable()
export class EmailValidator {

  constructor(private api:API) {}

  /* static */ checkEmail(control: FormControl,): any {
    return this.api.checkUser(control.value).then(response => {
      response;
    });
  }
}

将其添加到 @NgModule()@Component() 中,具体取决于您希望它具有的范围

providers: [EmailValidator]

将其注入到您要使用它的组件中

export class MyComponent {
  constructor(private emailValidator:EmailValidator, fb:FormBuilder){}

  this myForm = fb.group({
    email: [], [this.emailValidator.checkEmail.bind(this.emailValidator)]
  });
}