3

我正在将一个项目从 angular2 RC4 迁移到 RC6,并且我有一个自定义表单验证器,它需要Http. 在迁移之前,我将ReflectiveInjector与 一起使用HTTP_PROVIDERS,但在 RC6 中,这不再可能,因为HTTP_PROVIDERS已弃用,不再存在。这是验证器中的静态方法:

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

只是替换HTTP_PROVIDERS没有HttpModule用,我在 stackoverflow 上发现了一个类似的问题(NG2 RC5: HTTP_PROVIDERS is deprecated)关于测试,但唯一的答案是特定于测试的。

如果此自定义验证器有其他或更好的解决方案,我如何手动“注入”Http或使用 RC6,我也对此持开放态度。HttpModule

提前致谢。

更新:该checkVat方法是静态的,这就是为什么我必须使用 ReflectiveInjector 而不仅仅是通过构造函数注入它,就像其他地方一样。自定义验证器的使用方式如下:

this.vatCtrl = new FormControl("", Validators.compose([Validators.pattern(this.vatService.vatPattern)]),VatValidator.checkVat);

UPDATE2:在 Günther Zöchbauer 的回答的帮助下,我将代码更改如下,使其在没有静态函数且无需手动注入的情况下工作:

验证者:

@Injectable()

导出类 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();
                });
            });
    }

}

}

在具有 FormControl 的组件中:

    constructor(private vatValidator: VatValidator) {

    this.vatCtrl = new FormControl("", Validators.compose([Validators.pattern(vatPattern)]), this.vatValidator.checkVat.bind(this.vatValidator));

}
4

3 回答 3

12
import { ReflectiveInjector } from '@angular/core';
import { Http, XHRBackend, ConnectionBackend, BrowserXhr, ResponseOptions, XSRFStrategy, BaseResponseOptions, CookieXSRFStrategy, RequestOptions, BaseRequestOptions } from '@angular/http';

class MyCookieXSRFStrategy extends CookieXSRFStrategy {}

...

let http =  ReflectiveInjector.resolveAndCreate([
        Http, BrowserXhr, 
        { provide: ConnectionBackend, useClass: XHRBackend },
        { provide: ResponseOptions, useClass: BaseResponseOptions },
        { provide: XSRFStrategy, useClass: MyCookieXSRFStrategy },
        { provide: RequestOptions, useClass: BaseRequestOptions }
      ]).get(Http);

当然,您仍然需要包含 HttpModule,享受吧!

于 2016-09-15T04:42:09.153 回答
2

如果您稍微更改验证器类,则不需要静态方法

@Injectable()
class PatternValidator {
  constructor(private http:Http){}

  // this is a method that returns a validator function  
  // configured with a pattern
  pattern(pattern) {
    return (control:Control) => {
      this.http.get(...)

    ...
    }
  }
}

你可以像这样使用它:

  • 将其注入到您的组件中,以便 DI 在 ( Http)中传递它的依赖项
constructor(private pattern:PatternValidator) {}
  • 传递它,bind(pattern)以便.this在验证器函数中继续工作
this.vatCtrl = new FormControl("", 
    Validators.compose([
        this.pattern(this.vatService.vatPattern).bind(this.pattern)
    ]), VatValidator.checkVat);

另请参阅 以角度 2 手动注入 Http

于 2016-09-09T09:45:32.170 回答
0

在 RC5 之后,您可以做的是,

import { HttpModule} from '@angular/http';
@NgModule({
  imports:      [ BrowserModule,HttpModule ],  //<------HttpModule
  declarations: [ AppComponent],
  providers:    [service],

  bootstrap:    [ AppComponent ]
})

在服务或组件中,

import { Http, Response } from '@angular/http';
@Injectable()
export class service{
  constructor(private http:Http){}           //<----inject here

  // use http here
}
于 2016-09-09T08:28:58.557 回答