Ionic loadcontroller在我的http post上不起作用

qacovj5a  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(142)

你好,我有两个toastmessages,一个是当邮件发送时,另一个是当它失败时。我测试我的webform,但是当我按下发送按钮时,它有时会在消息显示之前有一个延迟。现在我想使用loadcontroller,当用户点击按钮时,它会消失,当邮件发送或发送失败时。

constructor(private http: HttpClient, private toastController: ToastController, private loadingCtrl: LoadingController) { }

  sendMail(formData){
    this.simpleLoader();
    return this.http.post('https://portfolio500.herokuapp.com/sendmail', formData).subscribe({

      next: () => {
        this.dismissLoader();
        this.showToast('email succesvol verzonden');
    },
      error: () => {
        this.dismissLoader();
        this.showToast('email verzenden mislukt.');
    }
    });
    }

  async showToast(message: string){
    const toast = await this.toastController.create({
      message,
      duration: 4000,
      buttons: [ {
        text: 'X',
        role: 'cancel'
      }]
    });
    toast.present();
  }

  simpleLoader() {
    this.loadingCtrl.create({
        message: 'email wordt verzonden'
    }).then((response) => {
        response.present();
    });
}

dismissLoader() {
  this.loadingCtrl.dismiss().then((response) => {
      console.log('Loader closed!', response);
  }).catch((err) => {
      console.log('Error occured : ', err);
  });
}
}
hgncfbus

hgncfbus1#

加载ctrl是承诺和您的http请求得到返回之前,您的加载初始化。
试试这个:

loading: any;

    async sendMail(formData) {
        await this.presentLoading();
        return this.http.post('https://portfolio500.herokuapp.com/sendmail', formData).subscribe({
    
          next: async() => {
            await this.stopLoading();
            this.showToast('email succesvol verzonden');
          },
          error: async() => {
            await this.stopLoading();
            this.showToast('email verzenden mislukt.');
          }
        });
      }

    async presentLoading(m = 'Please Wait') {
        this.loading = await this.loadingController.create({
          message: m,
          showBackdrop: true
        });
        await this.loading.present();
      }

    async stopLoading() {
        if (this.loading) {
          await this.loadingController.dismiss();
        } else {
          setTimeout(async () => {
            await this.loadingController.dismiss();
          }, 2000);
        }
      }

相关问题