Nav in Injectable() class, using ViewChild is undefined?

Here, Im trying to create a Toast Service. Seems Having NavController for injectable is not working, and now i changed my code to use ViewChild. However, i get undefined for this.nav.

What am i doing wrong?

import {Injectable, ViewChild} from '@angular/core';
import {Toast, Nav} from 'ionic-angular';

export class ToastService {
  toast: Toast;
  @ViewChild(Nav) nav: Nav;
  constructor (

  ) {
    // init
    this.toast = Toast.create({
      message: "",
      duration: 3000
  show(message: string) {
    console.log('toast show called');
1 Like

Hey @ozexpert checkout this answer. Why can't I import NavController and ViewController into Service or App?

I hate the idea of passing nav as param, but will try app.getActiveNav ()

Is there a reason you’re not using the ionic-native toast plugin?

Yeah my app also shares code with electron. Trying to minimize cordova plugins. There’s actually no reason to use toast cordova plugin. UI for toast can be easily implemented in Js/html level.

Good luck then. I’ve decided that every time I try to touch the UI from a Service, I end up regretting it in the end.

@rapropos i try to minize the code. If having nav controller inside the component i would have lot of redunt code in every Page component, right?

If the toast was a component on its own, you could just put a <toast> element in the template of whatever skeleton surrounds all your other pages.

1 Like