簡體   English   中英

顯示驗證錯誤消息(Spring Boot,Angular CLI 7)

[英]Display validation error messages (Spring Boot, Angular CLI 7)

我正在嘗試顯示從后端(Spring Boot)傳遞到前端(Angular CLI 7)的錯誤。 錯誤由 ResponseEntity 傳遞。

我有一個檢查響應的 function

    OnRegister(user) {
      this.errorMessages = [];
      this.authenticationService.register(user)
      .subscribe(resp => {
          this.router.navigateByUrl('/pages/authentication/login');
        }, error => this.errorMessages.push(error.error)
      );
      console.log(this.errorMessages);
    }

數組 errorMessages 保存“ValidationMessage”對象 - 字段:字段、消息。

控制台 output:

[]
  0: Array(3)
    0: {field: "password", message: "Field password cannot be null."}
    1: {field: "passwordConfirm", message: "Field passwordConfirm cannot be null."}
    2: {field: "email", message: "Field email cannot be null."}

我怎樣才能從這個數組中獲取一個元素。

不能只使用:

<li *ngFor="let error of errorMessages">
  <p>{{error.message}}</p>
</li>

您需要將來自 spring 的消息迭代到 string[] state 命名錯誤中。

error: (error: (any)) => {
          let errors = error.error.errors;
          for (let i = 0; i < errors.length; i++) {
            this.error.push(errors[i].field + " " + errors[i].message);
          }
        }

然后,您可以像這樣在組件 html 中顯示它們

<div class="alert alert-danger" role="alert">
   <ul>
      <li *ngFor="let error of error">{{error}}</li>
   </ul>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM