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


#1

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';


@Injectable()
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');
    
    this.toast.setMessage(message);
    this.nav.present(this.toast);
  }
}

#2

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


#3

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


#4

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


#5

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.


#6

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.


#7

@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?


#8

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.