Angular2 How to display error message from backend

der*_*zay 1 laravel lumen angular

I want to display the error message in a bootstrap alert. I'm using angular2 as my frontend and lumen as my backend.

Frontend

<div class="alert alert-danger"> 
    // Display error message here 
</div>
Run Code Online (Sandbox Code Playgroud)

I want the response from the validate function displayed on the frontend

public function uploadImage(Request $request)
{
    $this->validate($request, [

        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:60000',

    ]);
}
Run Code Online (Sandbox Code Playgroud)

component.ts

uploadFile(): void {

let file = this.fileInput.nativeElement;
if (file.files && file.files[0]) {
  let fileToUpload = file.files[0];
  this.getInfoService
    .uploadImage(fileToUpload)
    .subscribe(
      data => console.log("DATA", data),
      err => console.log(err),
      () => console.log("()",'yay')
    );
}
Run Code Online (Sandbox Code Playgroud)

}

in my service

uploadImage(fileToUpload: any) {

let input = new FormData();
input.append("image", fileToUpload);
return this.http.post('http://Api.app/api/v1/uploadImage', input)
  .map(
    (response: Response) => {
      console.log("Upload img service", response);
    }
  );
Run Code Online (Sandbox Code Playgroud)

}

The response

响应是什么样的

jac*_*414 5

我会将错误消息(如果返回)设置为等于一个角度变量,然后检查该变量是否存在以决定是否显示它。

<div *ngIf="errors" class="alert alert-danger"> 
    {{ errors }} 
</div>
Run Code Online (Sandbox Code Playgroud)

成分:

uploadFile(): void {
  this.errors = null;

  let file = this.fileInput.nativeElement;

  if (file.files && file.files[0]) {
    let fileToUpload = file.files[0];
    this.getInfoService
      .uploadImage(fileToUpload)
      .subscribe(
        data => {
          console.log("DATA", data)
        },
        err => {
          this.errors = err
        }
      );
  }
}
Run Code Online (Sandbox Code Playgroud)

要正确显示所有消息,您可能需要遍历 JSON 响应并连接字符串,或将各个消息作为<li>元素添加到无序列表中。