How do I change local notification data on trigger?


#1

I’m trying to change the data in my local notification using the on.(“trigger”) method. However, it keeps showing the same notification again and again with the same data. This way I know the notificaiton is working but it’s not changing data on the trigger.

Ionic Framework: 3.1.1
Node: 6.10.0
OS: Windows 7
Ionic CLI: 3.0.0
Cordova CLI: 7.0.1

I’m using the following code for the trigger:

 ionViewDidLoad() {

        // Get the JSON data from our itemApi
        this.itemApi.getItems().then(data => {

            this.items = data;

            let randomNumber = Math.floor(Math.random() * this.items.length)
            
            // Select the random object an pass it to the oneItem object
            this.oneItem = this.items[randomNumber];

        });

        // --------------------------------------------------------------------------------------
        // ---- Function for changing data on trigger
        // --------------------------------------------------------------------------------------
        // Creates a callback function on the schedule trigger - populates the notification with new data
        this.localNotifications.on("trigger", function() {

                // Get the JSON data from our itemApi
                this.itemApi.getItems().then(data => {

                    this.items = data;

                    let randomNumber = Math.floor(Math.random() * this.items.length)

                    // Select the random object an pass it to the oneItem object
                    this.oneItem = this.items[randomNumber];

                    // The notification
                    let notification = {
                        id:1,
                        title: this.oneItem.word,
                        text: this.oneItem.description,
                        every: "minute"
                    };

                    this.notifications.push(notification);

                    this.notifications.update(this.notifications);

                });
        });
    }

Do you know why it’s not working?


#2

Any time I see somebody post code containing the word ‘function’, I suspect an execution context loss. What happens if you replace the trigger handler with an arrow function?


#3

Did you try same code with ngOnInit() ?
I suspect Angular code runs before Ionic code.
To me, your code is clean, just an issue with async code.

But show the template view please, it will help debug faster.


#4

after

this.items = data;
// put
console.log(this.items);

I’m pretty sure it will return undefined or null.

you tell me?