Franch
Franch

Reputation: 651

Global component Ionic 3

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:

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

Answers (1)

Sergey Rudenko
Sergey Rudenko

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

Related Questions