Inject custom service into a custom Validator

为君一笑 提交于 2019-12-20 12:39:08

问题


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

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

  }

}

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)

What I'm doing wrong?

Thanks


回答1:


@Injectable()
export class EmailValidator {

  constructor(private api:API) {}

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

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


来源:https://stackoverflow.com/questions/42646440/inject-custom-service-into-a-custom-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!