【发布时间】:2021-06-09 22:14:55
【问题描述】:
在我的 Angular-11 应用程序中,我有以下代码:
login.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 函数:
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": "akwetey@gmail.com",
}
}
}
登录失败:
{
"success": false,
"message": "Email is Required!",
"data": []
}
登录成功后就可以正常使用了。它显示来自后端 api JSON 响应的消息,如下所示:
title: data.message,
但是对于失败或错误,它会不断带来相同的消息“Internal Server Error”。但是来自后端 api JSON 响应的自定义消息,例如:“需要电子邮件”,如端点
"message": "Email is Required!",
当我从 Angular 执行此操作时:
this.toastr.error(error.message);
我如何获得此要求并从 api 响应中获取自定义消息,而不是
“内部服务器错误”消息
谢谢
【问题讨论】:
标签: angular