承诺的拒绝是在角度2/4中抛出错误

时间:2017-08-21 07:36:16

标签: angular typescript angular2-forms angular-promise

我已经定义了这样的异步验证器函数。

Parent

投掷低于错误(可能在拒绝

  

无法读取属性&ng-ngOriginalError'为null

如何摆脱这个错误? 感谢

Plnkr:https://embed.plnkr.co/VSHXGKiMGUWEhy8neyXU/

2 个答案:

答案 0 :(得分:3)

通常,如果您拒绝接受承诺,最好使用Error

拒绝承诺
reject(new Error('User is not vikash (whatever descriptive message what went wrong)'));

编辑由于您正在尝试实施异步验证程序,因此您需要resolve承诺null不要拒绝它以表明验证正常。

static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (control.value === 'some_text') {
              resolve({ shouldBeUnique: true });
            } else {
              resolve(null); // resolve
            }
        }, 2000);
    });
}

Demo

答案 1 :(得分:0)

在角度形式验证中,当字段有效时,您应该传递null。它有点令人困惑,但这是怎么回事。您可以详细了解herehere

我附上了你从我这里分叉的笨蛋。我只更改了在归档有效时返回null,并且ValidationErrors当它无效时。 另外要更清楚地了解已归档的验证状态Iv&#39; e在html中添加了错误对象。

https://embed.plnkr.co/t0gniM/

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      Please open developer console to chek the exception <br>
      Type anything and click anywhere other than the textbox<br><br>

      <form [formGroup]="formObj">
      <input type="text" id="username" formControlName="username" placeholder="Username" />
      {{formObj.controls['username'].errors|json}}

      </form>
    </div>
  `,
})
export class App {
  name:string;
  shouldBeUnique(control:AbstractControl):Promise<ValidationErrors|null>{
    return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (control.value === 'vikash') {
                  console.log('---matched--');
                    resolve(null);
                }else{
                resolve({ shouldBeUnique: true });
                }
            }, 1000);
        });
  }

  formObj = new FormGroup({
    username: new FormControl('', [
      Validators.required
    ], [
      this.shouldBeUnique
      ])
  });
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

}

@NgModule({
  imports: [ BrowserModule,FormsModule,ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

希望有所帮助。

相关问题