组件中的角度服务器端登录错误处理?

时间:2020-01-18 01:31:56

标签: javascript angular typescript rxjs observable

我有登录服务器的代码。因此,我使用有角度的HTTP客户端和授权服务。如果我将错误的数据发布到服务器,则会从服务器获得预期的响应,但是由于内部角度不佳,执行必须停止。

记录以下控制台输出:

post data=login (in auth.service.ts)

ERROR 
Object { headers: {…}, status: 401, statusText: "Unauthorized", url: "http://localhost/login", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:3000/login: 401 Unauthorized", error: {…} }
(in core.js:4002)

​

任何人都可以解释原因吗?

谢谢。

在使用中

login(loginUrl: any, body: { pass: string }) {
  console.log('post data=login');
  return this.http.post(loginUrl, body, httpOptions);
}

在组件中

login(): void {
    this.authService.login(loginUrl, data).subscribe((serverLoginResponse: any) => {

       // successful log in, continue to do stuff.

      }, (serverLoginError: any) => {
        console.log('error in subscribe err');
        console.log(serverLoginError.statusText, serverLoginError.status);
        if (serverLoginError.status === 401) {
          this.loginForm.controls['password'].setErrors({invalid: true});
        }
      });
     });
  }

在模板中

<input #passwordField id="password" class="form-control" type="password" formControlName="password" required>
<div [hidden]="!loginForm.controls['password'].hasError('invalid')" class="alert alert-danger">
   There is no user account matching the entered data! Try again.
</div>

1 个答案:

答案 0 :(得分:0)

首先,按照Angular的指南Making a POST request使用其内置的HttpClient模块,它被指示使用错误处理程序通过管道传递到catchError。尝试看看是否可行。

另外,根据我的个人经验,我建议在类似Promise的对象下封装HttpClient模块。例如:

login(url: string, data: { pass: string }) {
    return new Promise((resolve, reject) => {
        this.http.post(url, data, options || {})
            .subscribe(
                response => resolve(response),
                err => reject(err)
            );
    });
}

然后,您的组件函数将如下所示:

login() {
    this.authService.login(loginUrl, data)
        .then((serverLoginResponse: any) => {
            console.log('Request successful, check login results.');
        })
        .catch((serverLoginError: any) => {
            console.error('error in subscribe err');
            // I would first examine the error response
            console.log(serverLoginError);
        });
    });
}