【问题标题】:Importing Ionic ToastController into TS Class将 Ionic ToastController 导入 TS 类
【发布时间】:2019-01-18 21:12:08
【问题描述】:

我不知道我想做的事情是否可能,甚至是否聪明。我正在做一个 Ionic 3 项目,我想在一个类中包含“Toast”功能,以便我可以建立默认值并从任何地方访问它。

  1. 如何访问从我的类定义中的“ionic-angular”导入的 ToastController 中的方法?通过构造函数传递它意味着当我想使用我的类创建新对象时必须传递它,这对我来说没有意义。
  2. ToastController create()present() 中有两个方法。如果每当我通过从应用程序的其他地方调用 new Toast("My Toast Message") 创建 Toast 对象的新实例时,toast 消息会按预期出现在 UI 中,这将是非常酷的。我不知道这是否可能,或者我是否需要返回我在代码中概述的“创建”对象。

谢谢

import { ToastController } from 'ionic-angular';

export class Toast {

    private toast: {
        message: string;
        duration: number;
        showCloseButton: boolean;
        position: string;
        cssClass: string;
    }

    public toastCtrl: ToastController; // this doesn't do anything I don't think

    constructor(message: string, 
                duration: number = 3000, 
                showCloseButton: boolean = true, 
                position: string = 'top',
                cssClass: string = 'brand-toast') {

        this.toast = {
            message: message,
            duration: duration,
            showCloseButton: showCloseButton,
            position: position,
            cssClass: cssClass,
        }

        return this.toastCtrl.create(this.toast);

        // would be cool to instead call this:
        // this.toastCtrl.create(this.toast).present();

    }

}

【问题讨论】:

    标签: typescript class ionic-framework ionic3


    【解决方案1】:

    首先,你的 toast 必须是一个提供者,你可以在任何你想要的地方使用它。

    import { ToastController } from 'ionic-angular';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class ToastProvider
    

    您可以创建方法来自定义 toast 或调用默认 toast

    private isShowToast: boolean = false;
    
    public showCustomToast(toast: any) {
        if (this.toast !== undefined && this.isShowToast) {
          this.toast.dismiss();
          this.isShowToast = false;
        }
    
        let customToast = this.toastCtrl.create({
          message: toast.message,
          duration: toast.duration
        });
    
        customToast.present();
        this.isShowToast = true;
      }
    
    public showDefaultToast(){
        if (this.toast !== undefined && this.isShowToast) {
          this.toast.dismiss();
          this.isShowToast = false;
        }  
    
        this.toast.present();
        this.isShowToast = true;
    }
    

    不要忘记将您的 ToastProvider 作为提供程序导入到您的组件和 app.module.ts 中

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2019-08-30
      • 2019-07-04
      • 2018-04-10
      • 2020-06-30
      • 2019-06-22
      相关资源
      最近更新 更多