I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application.
- Is there a way for me to utilize methods from the ToastController imported from 'ionic-angular' within my class without passing it through the constructor every time I create a new object? It seems counterintuitive to me.
- The ToastController has two methods, namely
create()
andpresent()
. It would be great if whenever I instantiate a new Toast object by callingnew Toast("My Toast Message")
elsewhere in the app, the toast message automatically displays on the UI. I'm not sure if this is achievable or if I need to return the created object as shown in the code snippet.
Thank you
import { ToastController } from 'ionic-angular';
export class Toast {
private toast: {
message: string;
duration: number;
showCloseButton: boolean;
position: string;
cssClass: string;
}
public toastCtrl: ToastController; // I don't believe this line serves any purpose
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);
// Instead of returning, it would be neat to directly call:
// this.toastCtrl.create(this.toast).present();
}
}