During the migration of my project from angular2 RC4 to RC6, I encountered an issue with a custom Form Validator that requires the use of Http
.
Previously, I utilized ReflectiveInjector
along with HTTP_PROVIDERS
, but in RC6, this approach is not feasible anymore as HTTP_PROVIDERS
has been deprecated and no longer available.
The following is the static method in the Validator:
static checkVat(control: FormControl) {
let checkVatUrl = "http://localhost:8080/checkvat";
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
let authHttp = new AuthHttp(new AuthConfig(), http);
if (control.value === "") {
return new Observable((obs: any) => {
obs.next(null);
obs.complete();
});
} else {
return authHttp.get(checkVatUrl + "/" + control.value)
.map((data: Response) => {
if (data.json().valid) {
return null;
} else {
let reason = "isNotValidVat";
return {[reason]: true};
}
})
.catch(function (e) {
return new Observable((obs: any) => {
obs.complete();
});
});
}
}
Replacing HTTP_PROVIDERS
with HttpModule
did not resolve the issue. I came across a similar problem on stackoverflow (NG2 RC5: HTTP_PROVIDERS is deprecated) related to testing, but the solution provided was specific to testing.
If there is a better or alternative solution for this custom Validator in RC6, I am open to suggestions.
Thank you in advance.
UPDATE:
The checkVat
method is static, which is why I had to use ReflectiveInjector instead of injecting it via the constructor like in other cases.
The custom Validator is used as follows:
this.vatCtrl = new FormControl("", Validators.compose([Validators.pattern(this.vatService.vatPattern)]),VatValidator.checkVat);
UPDATE2: Following Günther Zöchbauer's answer, I made the following changes to make it work without a static function and eliminate the need for manual injection:
The Validator:
@Injectable()
export class VatValidator {
constructor(private http: Http) {
}
checkVat(control: FormControl) {
let checkVatUrl = "http://localhost:8080/checkvat";
let authHttp = new AuthHttp(new AuthConfig(), this.http);
if (control.value === "") {
return new Observable((obs: any) => {
obs.next(null);
obs.complete();
});
} else {
return authHttp.get(checkVatUrl + "/" + control.value)
.map((data: Response) => {
if (data.json().valid) {
return null;
} else {
let reason = "isNotValidVat";
return {[reason]: true};
}
})
.catch(function (e) {
return new Observable((obs: any) => {
obs.complete();
});
});
}
}
}
In the component containing the FormControl:
constructor(private vatValidator: VatValidator) {
this.vatCtrl = new FormControl("", Validators.compose([Validators.pattern(vatPattern)]), this.vatValidator.checkVat.bind(this.vatValidator));
}