在静态内部注入http或服务

时间:2017-01-26 04:13:13

标签: angular typescript

我正在通过GlobalValidaitor.ts文件对angular2进行验证我将所有需要的额外方法放在其上

import { FormControl } from '@angular/forms';
import { Http } from '@angular/http';
import { Api } from '../providers/api';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';


export class GlobalValidator {


   constructor(public Api: Api) {

  }



  public  static checkEmailExisit(control: FormControl): any {
     return new Promise(resolve => {

      //Fake a slow response from server

      let  senddata: {email?: string} = {
        email : control.value
      };


      let seq = this.Api.post('phones/offers', senddata).share() ;
    seq
     .map(res => res.json())
     .subscribe(res => {
     resolve(res);
     });

    });

  }



  static mailFormat(control: FormControl): any {

    var EMAIL_REGEXP = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;

    if (control.value != "" && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
        return { "incorrectMailFormat": true };
    }

    return null;
}




}

并且因为它的静态不考虑API 我将感谢帮助角度2而不是最后一个版本它应该使用HTTP_PROVIDER并直接注入函数 但对于最后一个版本的角度它不起作用我事件不能导入HTTP_PROVIDER

2 个答案:

答案 0 :(得分:2)

最好的方法是根本不使用静态。

删除静态并传递验证器,如

@NgModule({
  providers: [GlobalValidator],
})
constructor(private globalValidator:GlobalValidator) {}
  ... 
  myEmail: [globalValidator.emailExists.bind(globalValidator)]
  ...

答案 1 :(得分:-1)

我可以在静态内部注入http,我可以按照以下方式执行

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



export class GlobalValidator extends CookieXSRFStrategy{



   static checkUserEmail(control: FormControl): any {
    let data :any ;
     let http =  ReflectiveInjector.resolveAndCreate([
             Http, BrowserXhr,
             { provide: ConnectionBackend, useClass: XHRBackend },
             { provide: ResponseOptions, useClass: BaseResponseOptions },
             { provide: XSRFStrategy, useClass: GlobalValidator },
             { provide: RequestOptions, useClass: BaseRequestOptions }
           ]).get(Http);


    var body = 'email='+control.value;
     var headers = new Headers();
     headers.append('Content-Type', 'application/x-www-form-urlencoded');

    let reques=  http
       .post('http://www.etc.cc/ChekEmail',
         body, {
           headers: headers
         }).share() ;


      reques   .map(res => res.json())
         .subscribe(res => {
           console.error('connected :', res.ishere);


         }, err => {
             console.error('ERROR in connection :',  JSON.stringify(err));
           });

  }

感谢您寻求帮助