Background Notifications: 'on' does not exist on type 'Push'


#1

While trying to integrate background notifications on my app. I have found that the code example provided by the docs here doesn’t work with the flow of the other Push code samples. So by applying this.push.on I get a TypeScript error stating Property 'on' does not exist on type 'Push'.

Do I need to add push.finish() to this.push.register() or this.push.rx.notification()? My code below, with the background notification code sample from the documentation that I get TypeScript error’s.

this.push.register().then((t: PushToken) => {
    return this.push.saveToken(t);
  }).then((t: PushToken) => {
    console.log('Token saved:', t.token);
});

this.push.rx.notification()
  .subscribe((msg) => {
    alert(msg.title + ': ' + msg.text);
  });

push.on('notification', function(data) {
      // do something with the push data
      // then call finish to let the OS know we are done
      push.finish(function() {
          console.log("processing of push data is finished");
      }, function() {
          console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
      }, data.additionalData.notId);
  });

#2

Shouldn’t you use this.push.on ???


#3

Good question! But if you read the last sentence in the first paragraph of my post you will see that I have tried…


#4

I know that this Push works only on the device itself only, so i use this before codes reach the push.on:

if (this.platform.is('core')) {
  return false;
}

The ‘core’ platform appears only on a desktop device, means when you run ‘ionic serve’.


#5

Everywhere you have push, it should be this.push


#6

Ah! I recent thread with the same issue as me!

I’m assuming doing this is required for the push notifications to work at all on iOS, as Android works just fine and nothing is happening on iOS.

Anyone have any idea how to use the piece of code provided here?


#7

The code related to this topic is for the code that will handle the background notification so it doesn’t crash the app. If you have the app open in the background, and you receive a notification, if you don’t act within 30 seconds the app will crash. And no this code just handle’s background notifications. The other code sample’s from that documentation will enable push notifications.

FYI, I was having issue’s getting Push Notifications working, and got it to work by updating my Ionic 2 project to the latest version compatible with 2.0.0-rc6. And by following the steps in the documentation I got everything working.


#8

Okay, so where exactly does that code go to prevent killing the app?

I also suddenly started receiving the notifications on my iPhone while testing on Android, so woohoo for that working but I’m not sure what I did haha.

Update: Just tested, and it never actually killed the app even without that code.


#9

@webstaff you found out the answer from anyone at Ionic?


#10

Same issue/problem here, Any ideas? or solution with this code?

push.on(‘notification’, function(data) {
// do something with the push data
// then call finish to let the OS know we are done
push.finish(function() {
console.log(“processing of push data is finished”);
}, function() {
console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
}, data.additionalData.notId);
});

by adding this.push still do not work


#11

OP: I ran into this same issue recently, and have had no luck finding a solution. I almost wonder if the doc for Ionic 2 are net yet updated. I am just adding some detective work to the puzzle here, to see if someone else (official?) may be able to elaborate or clarify what I believe I am seeing

I took a peek under the hood at the following file:
node_modules -> @ionic -> cloud-angular -> dist -> esm -> index.js

Inside, you can see where the export members are coming from. Namely, search for push.

The following is the export PushRx.

var PushRx = (function (_super) {
    __extends(PushRx, _super);
    function PushRx() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PushRx.prototype.notification = function () {
        var _this = this;
        return Observable.fromEventPattern(function (h) {
            return _this.emitter.on('push:notification', function (data) {
                return h(data.message);
            });
        }, function (_) {
            // https://github.com/ReactiveX/rxjs/issues/1900
            // this.emitter.off(signal);
        });
    };
    return PushRx;
}(Rx));

It sure looks like it wants to use Push.on(notification, function(data) {}) function prototype / signature that is referenced back in the docs. So I wonder if you need to use this.push.rx.notification() to simulate push.on(); then you need to use this.push.finish() as you speculate in your original question.

Did you ever find a solution to what you were attempting to do? Just curious.

-LB


#12

So, was this ever resolved? I have the same problem, but I’m unsure of how to proceed. Updating all the plugins/ionic/cordova didn’t work.


#13

The .on(…) - function is intended to be called directly on the push plugin.

The push-plugin is available through this.push.plugin after you registered (this is important, before register is called this.push.plugin is just null, so be sure to always use it in the callback of the register function)

But if you are not using background notifications in you app it is sufficient to just use the this.push.rx.notifcation callback.

Hope this helps!


#14

Hello,

I Think you should use this.push.plugin.on, using plugin give you access to native plugin functions as mentioned here: https://docs.ionic.io/api/client/push/#plugin

The code will be

this.push.plugin.on('notification', function(data) {
	// do something with the push data
	alert(JSON.stringify(data));
	// then call finish to let the OS know we are done
	this.push.plugin.finish(function() {
	console.log("processing of push data is finished");
	}, function() {
	console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
	}, data.additionalData.notId);
});

#15

Hey, I have a solution…

There’s a bit of confusion here about push notifications and Ionic, the documentary can be a little confusing.

When you import “Push” there are two kinds,

  1. import { Push, PushObject, PushOptions } from '@ionic-native/push'; (From Ionic )
  2. import { Push, PushToken } from '@ionic/cloud-angular'; (also from Ionic )

Option 1 is the native code, where you will need to use “this.push.on(‘notification’ …)”.
Option 2 is the angular wrapper, which ties everything up for you. You won’t need to call “this.push.finish()” either, the wrapper will take care of it.
The code which worked for me (ios and android):

if (!platform.is('cordova')) { //if you are using a computer or simulator
                let alert = this.alertController.create({
                    title: "No FCM token",
                    subTitle: "A fake token has been assigned.",
                    buttons: ['OK']
                });
                alert.present();

                console.warn("Push notifications not initialized. Cordova is not available - Run in physical device");
                localStorage.setItem('pushNotificationToken', "THIS_IS_A_FAKE_TOKEN");
            }
            else if (platform.is('cordova')) {
                console.log("Calling register");
                this.register(); 
            }
        });
    }

    register() {
        this.push.register() //call to FCM/APNS to get your register token
            .then((t: PushToken) => {
                let alert = this.alertController.create({
                    title: "Fcm Token Assigned",
                    subTitle: t.token,
                    buttons: ['OK']
                });
                alert.present();              
                localStorage.setItem('pushNotificationToken', t.token);
                return this.push.saveToken(t); //save token. NB this is a method of Push from ionic/cloud-angular
            })
            .then((t: PushToken) => {
                console.log('Token saved');
            });
        
        this.push.rx.notification() //subscribe for notifications. This is the wrapper which handles everything for you, when a notification comes through this will run.
            .subscribe((msg) => {
                let alert = this.alertController.create({
                    title: "App in foreground?",
                    subTitle: "Was the app in the foreground when this notification came through? " + msg.raw.additionalData.foreground, //you could use this kinda functionality to adjust how to handle notifications appropriately.
                    buttons: ['OK']
                });
                alert.present();

                let alert = this.alertController.create({
            title: msg.title,
            subTitle: msg.text,
            buttons: ['OK']
        });
        alert.present();
            });
    }

Also note, for IOS you will need a p12 certificate for push notifications. Get one through following these links.
After that, you’ll need to enable Push Notifications in App Services and optionally remote notifications to allow background notifications for IOS.
Personally IOS is a pain, but once you’ve learned all the shenanigans you’ll be fine. Please read the full documents that I have linked so that you can understand the processes.

The boring stuff (specs)
My version specs:
Cordova 7.0.1
Node: 7.9.0
Ionic 2.2.3 (At present, Ionic V3.5.0 is out but I’ve found it buggy)
Typescript: 2.2.1
Ionic/app-scripts: 1.3.0

Good luck!

Let me know if you need anything or if I’m wrong about anything.
Happy coding!