使用Angular Material处理服务器端错误

时间:2020-06-09 09:44:41

标签: angular angular-material ngrx

我有一个表单,并且可以像这样处理服务器端错误。

  constructor(private store: Store<fromRoot.State>) {
    this.containerTypes$ = store.pipe(select(fromWelcome.getCts));
    this.errors$ = store.pipe(select(fromModal.getError) as any);
    this.errors$.subscribe(errors => {
      if (errors) {
        if (errors.username) {
          this.usernameError = errors.username;
          this.regForm.controls['username'].setErrors({usernameServerError: this.usernameError});
          // <-------- I want to call my mat-error here
        }
      }
    }
    );

    this.regForm = new FormGroup({
      username: new FormControl('', [Validators.required, Validators.minLength(5)]),
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8)])
    });

在.html中,我这样做:

<mat-error *ngIf="regForm.controls['username'].hasError('usernameServerError')"> {{usernameError}} </mat-error>

不幸的是,我尝试提交后收到错误消息,但该错误未出现在我的输入下。我需要先单击输入,或再次提交表单。收到表格中的错误后,如何显示错误?

1 个答案:

答案 0 :(得分:1)

我需要启用表单

  constructor(private store: Store<fromRoot.State>) {
    this.containerTypes$ = store.pipe(select(fromWelcome.getCts));
    this.errors$ = store.pipe(select(fromModal.getError) as any);
    this.errors$.subscribe(errors => {
      if (errors) {
        this.regForm.enable() // <---- here
        if (errors.username) {
          this.usernameError = errors.username;
          this.regForm.controls['username'].setErrors({usernameServerError: this.usernameError});
        }
      }
    }
    );

    this.regForm = new FormGroup({
      username: new FormControl('', [Validators.required, Validators.minLength(5)]),
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8)])
    });