Angular 2无法读取null

时间:2016-11-23 03:50:16

标签: javascript angular

我正在学习承诺,我正在尝试一个简单的例子,但是我得到了错误。 promises角色只是检查是否已输入某个名称并在回调时产生布尔错误

  

无法读取属性'shouldBeUnique'为null

这是我的组件

import {Component, Inject} from '@angular/core';
import {FormGroup, Validators, FormBuilder} from '@angular/forms';
import {UsernameValidators} from './usernameValidators'

@Component({
    selector: 'signup-form',
    templateUrl: 'app/signup-form.component.html'
})
export class SignUpFormComponent {

    form: FormGroup;

    constructor(@Inject(FormBuilder) fb: FormBuilder) {
        this.form = fb.group({
            username: ['', Validators.compose([
                Validators.required,
                UsernameValidators.cannotContainSpace
            ]), UsernameValidators.shouldBeUnique],
            password: ['', Validators.required]
        })
    }

    get username(): any {return this.form.get('username');}
    get password(): any {return this.form.get('password');}

}

这是我的component.html

<form [formGroup]="form" (ngSubmit)="signup()">
    <div class="form-group">
        <label for="username">Username</label>
        <input 
                id="username"
                type="text"
                class="form-control"
                formControlName="username" placeholder="Username"
                >
        <div *ngIf="username.touched && username.errors">
            <div *ngIf="username.errors.shouldBeUnique" class="alert alert-danger">This username is already taken</div>
        </div>
</form>

这是我的验证员类,其中包含承诺

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

export class UsernameValidators {

    static shouldBeUnique(control: FormControl) {
        return new Promise((resolve, reject) => {
            setTimeout(function(){
                if (control.value == "mosh")
                    resolve({ shouldBeUnique: true});
                else
                    resolve(null);
            }, 1000)
        });
    }
}

由于

1 个答案:

答案 0 :(得分:2)

尝试使用safe navigation operator (?.)来防范属性路径中的null和undefined值。

<div *ngIf="username.touched && username.errors">
    <div *ngIf="username.errors?.shouldBeUnique" class="alert alert-danger">This username is already taken</div>
</div>

这应解决您当前遇到的错误。阅读Angular 2文档中的更多内容:

https://angular.io/guide/template-syntax#safe-navigation-operator