Runtime Error after handling 400

2019-02-27 16:32发布

Scenario:

The username and password is authenticated using WebApi 2 token authentication. If the credentials are correct, then token is returned. But, if the credentials are incorrect, 400 bad request is returned. In my Ionic 2 project, if I get the response, I navigate to the next page. If I get the error, I show my custom error message.

Issue:

The issue I'm facing is, if I enter the wrong credentials for the first time, the custom error message is shown. If I enter wrong credentials again, the custom error message is shown along with the ionic error message.

Here is my code:

login.ts

  doLogin() {
    if (this.Username !== undefined && this.Password !== undefined) {
      this.loading.present();
      this.authSrv.login(this.Username, this.Password).subscribe(data => {
        this.navCtrl.setRoot('HomePage');
        this.loading.dismiss();
      }, (err) => {
        this.errorMsg("Invalid Username/Password !" + err);
        this.loading.dismiss();
      });
    }
    else
      this.errorMsg("Please enter Username/Password");
  }

auth-service.ts

  login(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('username', username);
    urlSearchParams.append('password', password);
    urlSearchParams.append('grant_type', 'password');
    let body = urlSearchParams.toString()
    return this.http.post('http://' + this._api + '/postoken', body, { headers: headers }
    )
      .map(res => res.json())
      .map((res) => {
        if (res !== null) {
          localStorage.setItem('acess_token', res["access_token"]);
          localStorage.setItem('access_type', res["access_type"]);
          localStorage.setItem('expires_in', res["expires_in"]);
          this.loggedIn = true;
        }
        return res;
      });
  }

Screencast:

enter image description here

Error

enter image description here

Any advice would be helpful.

1条回答
ゆ 、 Hurt°
2楼-- · 2019-02-27 16:41

LoadingController can only be called once.

Note that after the component is dismissed, it will not be usable anymore and another one must be created.

This is causing the exception. You should create new loading everytime in doLogin.

doLogin() {
    if (this.Username !== undefined && this.Password !== undefined) {
      this.loading = this.loadingCtrl.create({ //create here
    content: 'Please wait...'
     });
      this.loading.present();
      this.authSrv.login(this.Username, this.Password).subscribe(data => {
        this.navCtrl.setRoot('HomePage');
        this.loading.dismiss();
      }, (err) => {
        this.errorMsg("Invalid Username/Password !" + err);
        this.loading.dismiss();
      });
    }
    else
      this.errorMsg("Please enter Username/Password");
  }
查看更多
登录 后发表回答