简体   繁体   English

Angular2用户名或电子邮件采用异步验证

[英]Angular2 username or email taken async validation

I need to implement async validation with github api. 我需要用github api实现异步验证。 I hope you help me. 我希望你帮助我。

        export class UsernameValidator {   
            static usernameTaken(control: FormControl): Promise<ValidationResult> {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {          
                        //How Can i use github Api like this: 
                        // if (control.value === "this._http.get('http://api.github.com/users/'+this.username)")) {
                        if (control.value === "David") {
                            console.log('username taken')
                            resolve({"usernameTaken": true})
                        } else {

                            resolve(null);
                        };                
                    }, 1000);
                });

            }
        }

Thank you. 谢谢。

This is implemented within a Reactive Form, but should be modifiable to a solution for the form driven method. 这是在Reactive Form中实现的,但应该可以修改为表单驱动方法的解决方案。

The validator is given the service that does the actual get via the API (a 404 is returned if a given user does not exist): 验证器被赋予通过API执行实际获取的服务(如果给定用户不存在则返回404):

export function usernameTaken(httpService: HttpService) {
    return control => new Promise((resolve, reject) => {
      console.log("in validator");
            //How Can i use github Api like this: 
            httpService.lookupUser(control.value).subscribe(data => {
              console.log(data);
              if(data.id) {
                resolve({ usernameTaken : true})
              } else {
                resolve(null);
              }
            }, (err) => {
              console.log("in error"+ err);
              if(err !== "404 - Not Found") {
                resolve({ usernameTaken : true});
            } else {
              resolve(null);
            }
              });
    });
}

The service itself looks like this: 服务本身如下:

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

   lookupUser(username: string): Observable<any> {
        return this.http.get("https://api.github.com/users/" + username)
            .map(this.extractData)
            .catch(this.handleError) as Observable<any>;
    };
 <...>
 }

And we inject in the service and apply the validator like so (third spot in the array is asyncValidators: 我们注入服务并像这样应用验证器(数组中的第三个位是asyncValidators:

constructor(private fb: FormBuilder, private httpService: HttpService) {
    this.name = 'Angular2',
    this.form = this.fb.group({
      username: ['', Validators.required, usernameTaken(this.httpService)]
    });

With the actual input looking pretty normal: 实际输入看起来很正常:

<input type="text" placeholder="Username" formControlName="username"/>

Here's a Plunker demonstrating the usage of the async validator: http://plnkr.co/edit/19lp0E9x6L4kPyX0ORg0?p=preview 这是一个使用异步验证器的Plunker: http ://plnkr.co/edit/19lp0E9x6L4kPyX0ORg0?p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM