Angular2 RC6 HttpModule手动注塑

时间:2016-09-09 08:17:36

标签: angular typescript angular2-forms angular2-injection

我正在将项目从angular2 RC4迁移到RC6,我有一个需要Http的自定义表单验证器。 在迁移之前,我将ReflectiveInjectorHTTP_PROVIDERS一起使用,但是对于RC6,由于HTTP_PROVIDERS已弃用,不再存在,因此不再可行。 这是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();
                });
            });
    }
}

只用HTTP_PROVIDERS取代HttpModule不起作用,我在stackoverflow(NG2 RC5: HTTP_PROVIDERS is deprecated)上发现了类似的关于测试的问题,但唯一的答案是针对测试的。

如何为RC6手动“注入”HttpHttpModule,如果此自定义验证器还有其他或更好的解决方案,我也会对此开放。

提前致谢。

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

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

UPDATE2: 在GüntherZö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));

}

3 个答案:

答案 0 :(得分: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,享受!

答案 1 :(得分: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);

另见 Inject Http manually in angular 2

答案 2 :(得分: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
}