本文介绍了将自定义服务注入自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自定义Angular 2表单 Validator 来检查用户是否存在于数据库中。

I'm trying to make a custom Angular 2 form Validator to check if a user exist on a data base.

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

This is the code of my custom form 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发出请求

And this is this is my custom service which is responsible for make the request to a node api on backend

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);
  }

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

When I try to validate a user this is the error that is showed

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()取决于您希望它具有什么范围

Add it to of @NgModule() or @Component() depending on what scope you want it to have

providers: [EmailValidator]

将其注入组件您要在哪里使用

Inject it to the component where you want to use it

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

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

这篇关于将自定义服务注入自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:04