首页 > 解决方案 > 如何处理从 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 还是有更复杂/正确的方法?

标签: angulartypescriptvalidation

解决方案


我认为 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,它不应该处理错误的传递和操作。


推荐阅读