laravel Angular2 如何显示来自后端的错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44032901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:59:31  来源:igfitidea点击:

Angular2 How to display error message from backend

laravelangularlumen

提问by derrickrozay

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

我想在引导程序警报中显示错误消息。我使用 angular2 作为前端,使用 lumen 作为后端。

Frontend

前端

<div class="alert alert-danger"> 
    // Display error message here 
</div>

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',

    ]);
}

component.ts

组件.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')
    );
}

}

}

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

}

}

The response

响应

What the response looks like

响应是什么样的

回答by Hymanel414

I would set the error message (if one is returned) equal to an angular variable and then check if that variable exists to decide whether to display it.

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

<div *ngIf="errors" class="alert alert-danger"> 
    {{ errors }} 
</div>

component:

成分:

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

To properly display all the messages, you'll likely need to loop through the JSON response and either concatenate the string, or add the individual messages as <li>elements in an unordered list.

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

回答by Nehal

In your http request you have to add a catch, something like following:

在您的 http 请求中,您必须添加一个捕获,如下所示:

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);
    })
  .catch(this.handleError);
}

Then add the handleError function:

然后添加handleError函数:

private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.of(error);
}

This handleError function will give you back whole response from server side. You can easily extract the error message from response body and assign it to a variable.

此 handleError 函数将从服务器端返回整个响应。您可以轻松地从响应正文中提取错误消息并将其分配给一个变量。

Then you can use interpolation to display the error message in bootstrap alert.

然后您可以使用插值在引导程序警报中显示错误消息。