将自定义服务注入自定义验证程序[英] Inject custom service into a custom Validator

本文是小编为大家收集整理的关于将自定义服务注入自定义验证程序的处理方法,想解了将自定义服务注入自定义验证程序的问题怎么解决?将自定义服务注入自定义验证程序问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我正在尝试制作自定义角度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)]
  });
}

本文地址:https://www.itbaoku.cn/post/1793768.html