首页 > 解决方案 > django + angular ,以角度显示 django 错误消息

问题描述

我正在使用 Django(drf) 和 Angular 8 创建一个练习应用程序,我想显示 Django 发送的错误消息,以防验证失败。

问题是,在使用 {observe: 'events'} 进行 HTTP 发布时,我无法使用 {observe: 'events'} 获取包含角度错误消息的响应正文,使用 {observe: 'events'} 作为进度条。

角码

postData(
    fileToUpload: File,
    empName: string,
    dept: string
  ): Observable<any> {
    const formData: FormData = new FormData();
    formData.append("file", fileToUpload, fileToUpload.name);
    formData.append("emp_name", empName);
    formData.append("dept", dept);
    return this.http
      .post(
        "http://localhost:8000/post/add",
        formData,
        { reportProgress: true, observe: "events" }
      )
      .pipe(tap((result) => {}, catchError(this.handleError<any>("postData"))));
  }

以上是在下面的代码中调用

public onSubmit(FileUploadFormData: NgForm) {
    let post: any = [];
    post = this.post;

    this.isFileUploading = true;
    const fileList: FileList = FileUploadFormData.value;
    this.empName = FileUploadFormData.value.empName;
    this.dept = FileUploadFormData.value.dept;

    this.uploadService.postData(this.file, this.empName, this.dept).subscribe(
      (response) => {
        switch (response.type) {
          case HttpEventType.Sent:
            console.log("inside sent");
            break;
          case HttpEventType.ResponseHeader:
            console.log("inside header");
            break;
          case HttpEventType.UploadProgress:
            this.percentage = Math.round(
              (response.loaded / response.total) * 100
            );
            console.log(`Uploaded! ${this.percentage}%`);

            break;
          case HttpEventType.Response:
            console.log("inside response", response.body);
            this.zone.run(() => {
              this.post = [];
              this.post = post;
              this.post.unshift(response.body);
            });
            this.percentage = 0;
        }
        if (this.percentage == 100) {
          this.percentage = 0;
          this.isFileUploading = false;
          console.log(response.body);

          this.toastr.success("Successfully posted");
        }
      },
      (error) => {
        console.log(error);
        this.loading = false;
        this.isFileUploading = false;
        this.toastr.error("failed posting");
      }
    );
    FileUploadFormData.reset();
  }

在调试时,当我在控制台中查找错误时,我得到以下信息

在此处输入图像描述

现在,如果我在表单中输入“销售”作为员工部门,那么来自 django 的错误消息就像

if not emp_dept.startswith("Dept"):

    return Response({"error": {'errorMessage': "Department name should start with 'Dept-' "}}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)

reponse of django is

{"error":{"errorMessage":"Department name should start with 'Dept-' "}}

现在我得到的是“发布失败”,我将如何以角度显示来自 Django 的这条错误消息?我没有得到 error.body 或 response.body,因此我可以使用 Django 发送的错误消息。

任何帮助将不胜感激!

提前致谢!

标签: javascriptpythondjangoangulartypescript

解决方案


更改错误处理功能

  (error) => {
    console.log(error);
    this.loading = false;
    this.isFileUploading = false;
    this.toastr.error("failed posting");
  }

至 :

  (error) => {
    console.log(error);
    this.loading = false;
    this.isFileUploading = false;
    this.toastr.error(error.error.errorMessage);
  }

推荐阅读