angular - 如何处理从 Angular 中的 http 调用返回的服务器端验证错误?
问题描述
通过遵循各种指南,我开发了一项服务,我可以调用该服务将登录详细信息发送到后端以进行验证和操作。我能够根据输入返回像样的错误代码,但那又如何呢?
export class AuthService {
constructor(private http: HttpClient) { }
getUserDetails(email, password){
// post to API server - return user info if valid
return this.http.post('http://localhost/api/listee/task_login.php', {
email,
password
}).subscribe(data => {
console.log(data, 'returned from login attempt')
var theData: any;
theData = data;
if (theData.post_err || theData.email_err)
console.log('ak;dsfj');
})
}
}
数据返回到一个类的函数......我如何在该范围内对表单元素进行操作?我需要以某种方式在正确的表单元素上触发 Angular 中的错误代码。我怎样才能访问它们?我需要手动选择 document.getElementByID 还是有更复杂/正确的方法?
解决方案
我认为 getUserDetail 应该是一个 Observable。
export class AuthService {
constructor(private http: HttpClient) { }
getUserDetails(email, password): Observable<any> {
// post to API server - return user info if valid
return this.http.post('http://localhost/api/listee/task_login.php', {
email,
password
})
// .subscribe(data => {
// console.log(data, 'returned from login attempt')
// var theData: any;
// theData = data;
// if (theData.post_err || theData.email_err)
// console.log('ak;dsfj');
// })
}
}
在您的组件中,您可以订阅此方法并读取结果。
someMethod(): void {
this.authService.getUserDetails(email,password).subscribe(result => {
//Do something with the result that you pass back in the component.
}
}
无需在服务中订阅,只需让组件处理订阅以及需要运行的任何其他逻辑。该服务应该做一件事,getUserDetails,它不应该处理错误的传递和操作。
推荐阅读
- python - exec() 赋值后的 Python 类型提示
- spring-boot - MvcResult 的 getResponse().getContentAsString() 返回一个空数组
- reactjs - React-Bootstrap 模式仅显示和删除最后一个映射元素
- database - 我的 BigTable 架构会导致热点吗?
- mongodb - 带有卷的mongo docker如何指定logpath和dbpath?
- bash - Shell 脚本在作为 AWS SSM 命令的一部分运行时出错
- javascript - 存储 Angular 应用的动作映射
- blazor-server-side - 使用作为参数传递给页面的数据渲染组件
- c - 如何让 printf 显示计算机之前执行的计算?
- ios - 以日期格式快速获取过去 7 天和接下来 7 天