Reputation: 651
I'm developing a PWA on ionic 3 with Angular 4 and I've failed multiple times trying to make a nice UI that show's in-app notifications about events.
I have a NotificationsService that is responsable for everything that has to do with getting the notification from Firebase.
My initial approach was to define a UI component (a.k.a notification-box) which would observe a property in the Notification Service and consume the notification provided by the service and display them nicely on top of the screen.
This sounds all nice and good but I created this component and had 3 issues:
Ionic 3 doesn't allow (AFAIK) a component to be 'global' and present in all app pages.
Including the tag of my component <notification-box></notification-box> on top of every page it's not a very good idea because components get instantiated and destroyed multiple times making it difficult to keep Subscriptions to the Observable notification property in the Service, and this could lead to a notification not arriving in between switching of pages.
If a notification where to arrive with a modal open, the notification would display behind the modal and my intent is to show notifications always on top.
I ended up using ToastController from ionic-angular which always displays on top no matter what (although it's a bit ugly and I want to switch to something like angular2-notifications).
How did Ionic achieve this "always on top" behaviour? Is there any way I can replicate that with a class of my own or Extend the ToastCtrl?
Upvotes: 2
Views: 917
Reputation: 9235
You can achieve what you want via provider and yes you will still need to inject such provider into every page that you want to see notifications in. You don't need to modify those pages' view (html templates) though.
I had similar need (to present "toast" inside of the app regardless of pages).
I solved this by making this provider a singleton provider (means we declare it at the app.module.ts in providers section) that is injected into every page (import and add to constructor):
import { Injectable } from '@angular/core';
import { ToastController } from 'ionic-angular'
@Injectable()
export class Toaster {
constructor (private toastCtrl: ToastController) {
}
presentToast(message, position, cssclass) {
let toast = this.toastCtrl.create({
message: message,
closeButtonText: "OK",
showCloseButton: true,
cssClass: cssclass,
position: position
});
toast.present();
}
presentSimpleToast(message, position) {
let toast = this.toastCtrl.create({
message: message,
duration: 3000,
position: position
});
toast.present();
}
}
Upvotes: 3