Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject custom service into a custom Validator

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

like image 600
Hanzo Avatar asked Mar 07 '17 10:03

Hanzo


1 Answers

@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)]
  });
}
like image 106
Günter Zöchbauer Avatar answered Sep 20 '22 19:09

Günter Zöchbauer