johnnyfittizio johnnyfittizio - 3 months ago 29
AngularJS Question

Ionic push: App breaks when push logic is inside the controller

THE SITUATION:

I am implementing Ionic Push for my Ionic app.

I already did all the setup and registration and everything is working fine.
I have already tested it and send a curl request on the device (both ios and android) and I am properly receive the notification.

So what?

I need to move the push logic inside the controller.
So i can retrieve the registrationId and save it in a table along with other user data. In order to use it later when needed.

But when i move from the code from the .run() in the app.js to the controller the app crash..

THE ERROR:

TypeError: Cannot read property 'init' of undefined
at http://localhost:8100/lib/ionic-platform-web-client/dist/ionic.io.bundle.js:5844:47


THE CODE:

var push = new Ionic.Push({
"debug": true
});

push.register(function(token) {
console.log("My Device token:",token.token);
alert(token.token);
push.saveToken(token); // persist the token in the Ionic Platform
});


THE QUESTION:

I really don't know what I am doing wrong.

The same code inside
$ionicPlatform.ready(function() {}
it works fine but not in controller...

I have already test the same logic in a fresh app and I could indeed put that logic in the controller.

Do you have some ideas why this time i can't?

Thank you very much!

Answer

Okay i found a solution.

I had to leave the push logic inside the run() method. Reading around it seems that's the way to go.

The solution was quite simple:

Injecting $rootScope inside the run method and use it to store the registrationId.

After that you can do whatever you want with it, for example send a post request to your api and save in db.

THE CODE:

.run(function($ionicPlatform, $rootScope) {

  $ionicPlatform.ready(function() {

    var push = new Ionic.Push({
        "debug": true
    });

    push.register(function(token) {

        console.log("My Device token:",token.token);

        push.saveToken(token);  // persist the token in the Ionic Platform

        $rootScope.registrationId = token.token;  !! <-- 

    });

  });
})
Comments