首页 > 解决方案 > 使用 Angular Material 处理服务器端错误

问题描述

我有一个表格,我会像这样处理我的服务器端错误。

  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>

不幸的是,我在尝试提交后出现错误,但它没有出现在我的输入下。我需要先点击输入,或者再次提交表单。在我的表单中收到错误后,如何立即显示我的错误?

标签: angularangular-materialngrx

解决方案


我需要启用我的表单

  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)])
    });

推荐阅读