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:
Error
Any advice would be helpful.
LoadingController can only be called once.
This is causing the exception. You should create new loading everytime in
doLogin
.