在我的 Angular-11 应用程序中,我有以下代码:
登录.ts:
onSubmit(){
this.isSubmitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
const formData = this.loginForm.getRawValue();
const data = {
email: formData.email,
password: formData.password
};
const headers = {
'Content-Type' : 'application/json'
};
this.isLoading = true;
return this.api.post('login', data, headers)
.pipe(first())
.subscribe(
data => {
this.tokenHandler(data);
},
error => {
this.toastr.error(error.message);
this.isLoading = false;
});
}
令牌处理函数:
tokenHandler(data: any){
this.token.setRoles(data.results.user.roles);
this.token.set(data.results.token_type + ' ' + data.results.access_token, data);
this.auth.changeAuthStatus(true);
this.router.navigateByUrl('/dashboard');
Swal.fire({
position: 'center',
icon: 'success',
title: data.message,
showConfirmButton: false,
timer: 3000
});
}
这些是我来自后端的登录成功和失败的 json api 响应:
登录成功:
{
"message": "You have successfully Logged In.",
"error": false,
"code": 200,
"results": {
"user": {
"id": 2,
"name": null,
"email": "[email protected]",
}
}
}
登录失败:
{
"success": false,
"message": "Email is Required!",
"data": []
}
登录成功后即可正常使用。它按照此处的说明显示来自后端 api JSON 响应的消息:
title: data.message,
但是对于失败或错误,它不断带来相同的消息“内部服务器错误”。但是来自后端 api JSON 响应的自定义消息,例如:端点中的“需要电子邮件”
"message": "Email is Required!",
当我从 Angular 执行此操作时:
this.toastr.error(error.message);
我如何获得这个要求并从 api 响应中获取自定义消息而不是
“内部服务器错误”消息
谢谢
检查文档,https://angular.io/api/common/http/HttpErrorResponse
error.message 是服务器错误。尝试console.log(error)
查看整个回报,或使用debugger;
太多。但是,error.error
在您的情况下,来自服务器的响应是。
提示:您可以使用拦截器来捕获错误。
https://www.tektutorialshub.com/angular/angular-http-error-handling/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句