2

I am trying to create a custom async validator for Angular 2 form control. I have a class which has a static method that checks the uniqueness of user on the server. I have created a service (UsersService), and injected Http Service in its constructor. I am trying to use this service(UsersService) in validator. I am using ReflectiveInjector.resolveAndCreate to resolve the dependency in my static validator method. I am getting following error "No provider for Http! (UsersService -> Http)" when the validator kicks in.

This is snippet from package.json

"dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",

    "angular-in-memory-web-api": "~0.2.4",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
    }

this is snippet from appmodule

@NgModule({
    imports:[ ...,HttpModule,...],
    declarations: [...],
    bootstrap:    [ AppComponent ],
    providers:    [ UsersService ]
})

this is snippet from Validator

export class UserValidators {
    static uniqueUser(control: FormControl) {
    let injector = ReflectiveInjector
        .resolveAndCreate([UsersService]);
    let userService = injector.get(UsersService);
        return new Observable((obs: any) => {
        obs.next({uniqueUser: true});
        obs.complete();
    });

this is snippet from UsersService

@Injectable()
    export class UsersService {
    constructor(private _http: Http) {}
    getUserByName(user: string) {
            return this._http.get("http://jsonplaceholder.typicode.com/users?user="+user)
                    .map( response => { console.log(response.json()); return response.json(); } );
    }
  • I tried the following as well let injector = ReflectiveInjector.resolveAndCreate([UsersService,Http,Jsonp ]); This results in the following error: No provider for ConnectionBackend! (UsersService -> Http -> ConnectionBackend) – Harshit Kapoor Feb 08 '17 at 21:23
  • any solution you got for this issue? – Krsna Kishore Jun 08 '17 at 09:04
  • See https://stackoverflow.com/questions/39243525/inject-http-manually-in-angular-2 – Walter Jul 06 '17 at 07:12

0 Answers0