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

问题描述 投票:1回答: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) {
        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>

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

angular angular-material ngrx
1个回答
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)])
    });
© www.soinside.com 2019 - 2024. All rights reserved.