Angular2用户名或电子邮件已通过异步验证 [英] Angular2 username or email taken async validation

查看:74
本文介绍了Angular2用户名或电子邮件已通过异步验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用github api实现异步验证.我希望你能帮助我.

I need to implement async validation with 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);
                });

            }
        }

谢谢.

推荐答案

这是在响应式表单中实现的,但应可修改为表单驱动方法的解决方案.

This is implemented within a Reactive Form, but should be modifiable to a solution for the form driven method.

向验证者提供通过API进行实际获取的服务(如果给定的用户不存在,则返回404):

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):

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

服务本身如下所示:

 @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>;
    };
 <...>
 }

然后我们像这样注入服务并应用验证器(数组中的第三点是asyncValidators:

And we inject in the service and apply the validator like so (third spot in the array is 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"/>

这是一个演示异步验证程序用法的插件: http://plnkr.co/edit/19lp0E9x6L4kPyX0ORg0?p =预览

Here's a Plunker demonstrating the usage of the async validator: http://plnkr.co/edit/19lp0E9x6L4kPyX0ORg0?p=preview

这篇关于Angular2用户名或电子邮件已通过异步验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆