本文介绍了angular2 异步验证 this.subscribe 异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试为用户名字段实现 async(isUnique) 和 sync(cannotContainSpace) 验证功能,我想看到此用户名已在使用中,如果文本框值为yener",则警告消息.同步功能工作正常,但我认为下面的 ss 可以帮助解释我的问题;

注意:canNotContain 同步验证函数工作正常,在我添加 isUnique 异步函数后发生此异常..

我该如何解决?

用户名验证器.ts

从'@angular/forms'导入{FormControl};导出类 UsernameValidator{静态 isUnique(控件:FormControl){返回新的承诺((解决,拒绝)=>{设置超时(功能(){调试器if(control.value =="yener")解决({isUnique:true})别的解决(空)},1000);});}静态无法包含空间(控件:FormControl){if(control.value.indexOf(' ')>=0)返回 { cannotContainSpace:true };返回空;}}

postmessage.component.ts

import { Component } from '@angular/core';从@angular/forms"导入 {FormControl,FormGroup,FormBuilder,Validators};从'../../validators/usernamevalidator'导入{UsernameValidator};@成分({moduleId:module.id,选择器:'post-message',templateUrl: '../../templates/postmessage.component.html'})导出类 PostComponent {表单:表单组;构造函数(FB:FormBuilder){this.form = fb.group({用户名:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace]),Validators.compose([UsernameValidator.isUnique])],电子邮件:['', Validators.required],消息:['',Validators.required]});}报名(){console.log(this.form.value);}}

这里是 html 模板:

<div class="form-group row"><label for="username" class="control-label col-md-2">名称:</label><div class="col-md-6"><input type="text" id="username" class="form-control" formControlName="username"><div *ngIf="form.controls['username'].touched && form.controls['username'].errors"><div class="alert alert-danger"*ngIf="form.controls['username'].errors.required">用户名是必需的.

<div class="alert alert-danger"*ngIf="form.controls['username'].errors.cannotContainSpace">用户名不能包含空格

<div class="alert alert-danger" *ngIf="form.controls['username'].errors.isUnique">此用户名已被使用.

</div>...

解决方案

很奇怪,我虽然我们可以在表单构建器初始化程序中使用Validators.compose()"函数作为异步参数,但 angular2 不同意我的看法..我刚换了;

用户名:['', Validators.compose([Validators.required,UsernameValidator.cannotContainSpace]),Validators.compose([UsernameValidator.isUnique])],

用户名:['', Validators.compose([Validators.required,UsernameValidator.cannotContainSpace]),UsernameValidator.isUnique],

它有效

我还想知道你是否想在一个组件中使用多个异步验证器使用

Validators.composeAsync()

功能.

I try to implement async(isUnique) and sync(cannotContainSpace) validation functions for username field, I want to see "this username already in use alert msg, if textbox value is "yener". sync function works fine but i think ss below can help explain my issue;

Note:canNotContain sync validation func works fine, aafter I added isUnique async function this exception occured..

how can I fix it ?

usernamevalidator.ts

import {FormControl} from '@angular/forms';

export class UsernameValidator{
    static isUnique(control:FormControl){
        return new Promise((resolve, reject)=>{
            setTimeout(function(){
                debugger
                if(control.value =="yener")
                    resolve({isUnique:true})
                else
                    resolve(null) 
            },1000);
        });        
    }
    static cannotContainSpace(control:FormControl){
        if(control.value.indexOf(' ')>=0)
            return { cannotContainSpace:true };
        return null;
    }
}

postmessage.component.ts

import { Component } from '@angular/core';
import {FormControl,FormGroup,FormBuilder,Validators} from '@angular/forms';
import {UsernameValidator} from '../../validators/usernamevalidator';

@Component({
    moduleId:module.id,
    selector: 'post-message',
    templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
    form : FormGroup;
    constructor(fb:FormBuilder){
        this.form = fb.group({
            username:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace]),Validators.compose([UsernameValidator.isUnique])],            
            email:['', Validators.required],         
            message:['', Validators.required]         
        });
    }
    signup(){
        console.log(this.form.value);
    }
 }

here is html template:

<form class="from-horizontal" [formGroup]="form" (ngSubmit)="signup()">
        <div class="form-group row">
            <label for="username" class="control-label col-md-2">Name:</label>
            <div class="col-md-6">
                <input type="text" id="username"  class="form-control" formControlName="username">
                <div *ngIf="form.controls['username'].touched && form.controls['username'].errors">
                <div class="alert alert-danger"
                *ngIf="form.controls['username'].errors.required">
                    User name is required.
                </div>
                <div class="alert alert-danger"
                *ngIf="form.controls['username'].errors.cannotContainSpace">
                    User name can not contain space
                </div>
                <div class="alert alert-danger" *ngIf="form.controls['username'].errors.isUnique">
                    This user name already in use.
                </div>
                </div>
            </div>...
解决方案

it's strange, i though we can use "Validators.compose()" function in form builder initializer as async parameters but angular2 dont agree with me..I just changed;

to

and it works

EDITED:also I figured out if you want to use multiple async validators in a component use

function.

这篇关于angular2 异步验证 this.subscribe 异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 08:06