Open a page after cliking on a push notification Ionic 2 iOS

648 Views Asked by At

Lately, I have been adding push notifications capability on my app. I am using FCN plugin found on this link and I developing using Ionic 2 framework. The notifications get delivered but when I tap on it it just opens the homepage of the app, and not the inner page that I need.

I have used this code

declare var FCMPlugin;
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;
  horoscopePage:any = HoroscopeHomePage;
  @ViewChild(Nav) nav: Nav;

   **********************

    FCMPlugin.onNotification(function(data){
      if(data.wasTapped){
        //Notification was received on device tray and tapped by the user.
        if(data.topic =="horoskopi" && data.type=="list"){

        console.log( JSON.stringify(data) );

        this.nav.push(this.horoscopePage);

        }

      }else{

        if(data.topic =="horoskopi" && data.type=="list"){

        console.log( JSON.stringify(data) );

        this.nav.push(this.horoscopePage);
        }
      }
  });
  });

Somehow this line of code this.nav.push(this.horoscopePage); doesn't do anything

When I use NavController instead it gives me this error:

MyApp_Host.html:1 ERROR Error: No provider for NavController!
    at injectionError (core.es5.js:1231)
    at noProviderError (core.es5.js:1269)
    at ReflectiveInjector_._throwOrNull (core.es5.js:2770)
    at ReflectiveInjector_._getByKeyDefault (core.es5.js:2809)
    at ReflectiveInjector_._getByKey (core.es5.js:2741)
    at ReflectiveInjector_.get (core.es5.js:2610)
    at AppModuleInjector.NgModuleInjector.get (core.es5.js:3578)
    at resolveDep (core.es5.js:11039)
    at createClass (core.es5.js:10903)
    at createDirectiveInstance (core.es5.js:10723)
2

There are 2 best solutions below

5
On

You can add public navCtrl: NavController into constructor then change code as

this.navCtrl.push(this.horoscopePage);
1
On

Well after I took a look at the official documentation of Ionic, I found out that we can't use NavController in app.component.ts because you can't inject NavController because any components that are navigation controllers are children of the root component so they aren't available to be injected. For more click here.

The reason that I was unable to push a new Page inside FCM.onNotifications() functions was that it changed the scope of application. The solutions was simple: just use the arrow function:

FCMPlugin.onNotification(
        (data)=>{
            if(data.wasTapped){ 
             //do something
            } 
            else {     
              //do something
           }
      });