如何在离子2 /角度2中处理400个错误请求

时间:2016-11-19 15:58:40

标签: angular ionic2

我有一个带登录页面的离子2应用程序。在我的登录页面中,我有一个功能(doLogin()),当用户点击登录按钮时会被点击。

当我提供正确的用户名和密码时,我会收到回复,并且可以将access_token存储在我的存储中。问题是,当我输入错误的凭据时,服务器返回400错误,并带有json respons:

{
  "error": "invalid_grant",
  "error_description": "The user name or password is incorrect."
}

如何捕获error_description以便我可以将其显示给用户?

我的登录页面中的功能如下所示:

doLogin(){
    this.authService.getAccessToken(this.userName, this.password, response => {
    console.log("My response: " + response);
      if(response.access_token != null) {
        this.storage.set('access_token', response.access_token).then(() => {
          console.log('Token is set');
          this.navCtrl.setRoot(HomePage);
        });
      }
      else {
        alert("To bad for you");
      }
   });
}

调用的服务是:

getAccessToken(usr:string, pwd:string, callback){
    let headers = new Headers();
    headers.append('Accept', 'application');
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    var data = "grant_type=password" 
                + "&username=" + usr
                + "&password=" + pwd

    let options = new RequestOptions({ headers: headers});

    this.http.post(authTokenUrl, data, options)
        .map(response => response.json())

        .subscribe(
            (response) => callback(response),
            (err) => callback(err.status)
        ),error => {
            console.log("Oooops!");
        }, () => {
            console.log("To Bad");
    };
}

0 个答案:

没有答案