問題描述
場景:
用戶名和密碼使用 WebApi 2 令牌身份驗證進行身份驗證.如果憑據正確,則返回令牌.但是,如果憑據不正確,則會返回 400 bad request.在我的 Ionic 2 項目中,如果我得到響應,我會導航到下一頁.如果我收到錯誤,我會顯示我的自定義錯誤消息.
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.
問題:
我面臨的問題是,如果我第一次輸入錯誤的憑據,則會顯示自定義錯誤消息.如果我再次輸入錯誤的憑據,自定義錯誤消息將與離子錯誤消息一起顯示.
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.
這是我的代碼:
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
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;
});
}
截圖:
錯誤
任何建議都會有所幫助.
Any advice would be helpful.
推薦答案
LoadingController 只能調用一次.
請注意,組件關閉后,將不再可用,必須創建另一個組件.
Note that after the component is dismissed, it will not be usable anymore and another one must be created.
這是導致異常的原因.您應該每次在 doLogin
中創建新的加載.
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");
}
這篇關于處理 400 后的運行時錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!