当用户尝试登录时,我正在显示 LoadingController。同时,正在调用 API。
当我从订阅中收到 SUCCESS 响应时,我可以关闭 LoadingController,但是当我收到 ERROR 响应时,我无法关闭。请帮忙!
我是一名专业的 Python 开发人员,也是 Ionic 的新手,一天前才开始使用。因此,请提供帮助。
import { Component, OnInit } from '@angular/core';
import { ToastController, LoadingController } from '@ionic/angular';
import { CallapiService } from '../callapi.service';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
userEmail = '';
userPassword = '';
loginUrl = 'login/';
loginMethod = 'POST';
postBody = {};
constructor(
public toastController: ToastController,
public loadingController: LoadingController,
private callApiService: CallapiService,
) { }
ngOnInit() {
}
async presentToast(displayMessage) {
const toast = await this.toastController.create({
message: displayMessage,
duration: 2000,
position: 'middle',
});
return await toast.present();
}
async presentLoading(loadingMessage) {
const loading = await this.loadingController.create({
message: loadingMessage,
});
return await loading.present();
}
loginUser() {
if (this.userEmail === '' || this.userPassword === '') {
this.presentToast('Email and password are required.');
}
else {
this.presentLoading('Processing...');
this.postBody = {
email: this.userEmail,
password: this.userPassword,
};
this.callApiService.callApi(this.loginUrl, this.postBody, this.loginMethod).subscribe(
(success) => {
console.log(success);
this.loadingController.dismiss();
},
(error) => {
console.log(error);
this.loadingController.dismiss();
}
);
this.loadingController.dismiss();
}
}
}
最佳答案
没有任何服务,
我在使用 Ionic 4 加载 Controller 时遇到了同样的问题。 经过反复试验,我得到了可行的解决方案。
由于加载 Controller 函数使用 async 和await,因为两者都是异步函数。
dismiss()函数将在present()函数之前调用,因为dismiss函数不会等到创建并呈现加载器,一旦函数调用,它就会在present()之前触发。
下面是工作代码,
loading:HTMLIonLoadingElement;
constructor(public loadingController: LoadingController){}
presentLoading() {
if (this.loading) {
this.loading.dismiss();
}
return new Promise((resolve)=>{
resolve(this.loadingController.create({
message: 'Please wait...'
}));
})
}
async dismissLoading(): Promise<void> {
if (this.loading) {
this.loading.dismiss();
}
}
someFunction(){
this.presentLoading().then((loadRes:any)=>{
this.loading = loadRes
this.loading.present()
someTask(api call).then((res:any)=>{
this.dismissLoading();
})
})
}
关于javascript - 无法在 Subscribe() 的错误响应中解除 LoadingController - Ionic 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059237/