【问题标题】:angular 5 async validator not working角度 5 异步验证器不工作
【发布时间】:2018-04-27 18:21:47
【问题描述】:

我正在验证服务器上是否存在手机号码 5.Si 我为此创建了一个自定义异步验证器。但它不工作也没有给出任何错误,并且它为表单字段提供待处理状态。任何帮助将不胜感激.这里是service.ts的代码

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { Observable } from "rxjs/Observable";

@Injectable()
export class SignupService {

constructor(private _http:HttpClient) {}
mobileExists(mobile:number):Observable<{}>{
return this._http.get("http://localhost/truck/api/web/user/verify-              exist?mobile="+mobile,{responseType:'json'});
}
}

这是我的 component.ts 的代码

            import { Component, OnInit } from '@angular/core';
        import {FormsModule, ReactiveFormsModule,AbstractControl, ValidationErrors,FormControl,Validators,FormGroup,AsyncValidatorFn} from "@angular/forms";
        import {SignupService} from "./signup.service";
        import {Observable} from "rxjs/Observable";
        import {map,take,debounceTime} from "rxjs/operators";

        @Component({
          selector: 'app-register',
          templateUrl: './register.component.html',
          styleUrls: ['./register.component.css'],
          providers: [SignupService]
        })
        export class RegisterComponent implements OnInit {
            signupForm: FormGroup;
            mobile: number;
            password: string;
            otp: number;
            public exist;

            constructor(public service:SignupService) {
            }

            ngOnInit() {
                this.signupForm = new FormGroup({
                    mobile: new FormControl('',
                        [Validators.required, Validators.minLength(10), Validators.maxLength(10)],this.mobileValidator.bind(this)),
                    password: new FormControl('',
                        [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
                    otp: new FormControl('',
                        [Validators.required, Validators.minLength(6), Validators.maxLength(6)]),
                });
            }

            mobileValidator(control: AbstractControl):any {

                return new Observable(resolve => {
                        this.service.mobileExists(control.value).subscribe(
                            data=>{
                                if (data['status'] == 'ok'){
                                    return null;
                                }else if(this.exist.status == 'exist'){
                                    return {mobileTaken:true};
                                }
                            },
                            error=>{
                             return   console.log(error)
                            },

                        );
                    }
                );
            }
        }

【问题讨论】:

  • 从 api 返回的数据是一个 json 数组,例如 {'status':'ok'}

标签: angular5


【解决方案1】:
  1. 在FormControl中使用mobile: new FormControl('', [Validators.required, Validators.minLength(10), Validators.maxLength(10)],[this.mobileValidator()]),所以AsyncValidator作为第三个参数,不需要调用bind。
  2. 使用地图,无需换行到新的 Observable 调用:mobileValidator() { return (control: AbstractControl): any =&gt; { return this.service.mobileExists(control.value).map(data =&gt; return (data['status'] == 'ok') ? null : { mobileTaken: true } )); } }

    1. 好文章在这里http://fiyazhasan.me/asynchronous-validation-in-angulars-reactive-forms-control/

【讨论】:

  • 如何在地图中捕捉到 200 以外的其他状态码?我试过了,如果状态码不是 200 就不行了。
  • @karoluS 在你的管道中使用 catchError((err: any) => {...})
猜你喜欢
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多