将自定义服务注入自定义验证程序

时间:2017-03-07 10:57:10

标签: forms validation angular custom-validators

我正在尝试制作自定义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)

我做错了什么?

由于

1 个答案:

答案 0 :(得分:11)

x.count()

将其添加到@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]