如何解决django + angular,以角度显示django错误消息
我正在创建一个使用Django(drf)和angular 8进行练习的应用程序,我想在验证失败的情况下显示Django发送的错误消息。
问题是,当使用{observe:'events'}进行HTTP发布时,使用{observe:'events'}进行进度,我无法使用{observe:event}获取包含错误消息的响应主体酒吧。
角度代码
(?!...)
上面是在下面的代码中调用
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"))));
}
在调试时,当我在控制台中查找错误时,我会得到以下提示
现在我是否以员工部门的形式输入“销售”,而不是来自Django的错误消息?
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的错误消息?我没有得到error.body或response.body,所以我可以使用Django发送的错误消息。
任何帮助将不胜感激!
谢谢!
解决方法
从以下位置更改错误处理功能
(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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。