I'm trying to create a new Id for a notification using the getAllIds()
method supplied by the $cordovaLocalNotification
plugin.
I have a notify
Class which has a method for creating a new Id and a subsequent method for creating a notification as below:
var notify = {
latestId: function() {
$cordovaLocalNotification.getAllIds().then(function(result){
return result.length;
})
},
setNotification: function(show) {
$ionicPlatform.ready(function() {
$cordovaLocalNotification.schedule({
id: notify.latestId,
title: show.name + " is out today!",
});
});
}
};
Where I try and assign the result using id: notify.latestId
It seems to be en empty promise object or something. I've tried loads of different design patterns but I think I am missing something fundamental. Any help would be much appreciated!
Edit: Whole factory for good measure.
.factory('Notifications', function($cordovaLocalNotification, $ionicPlatform) {
var notify = {
alertTime: function() {
t = new Date();
t.setSeconds(t.getSeconds() + 10);
return t;
},
latestId: function() {
var newId;
$cordovaLocalNotification.getAllIds().then(function(result){
console.log('Get all ids: ' + result) //Returned 2nd: 'Get all ids: 1,0,4,5,3,2'
newId = result.length;
console.log('New id: ' + newId);//Returned 3rd: 'New id: 6'
});
console.log('New id: ' + newId); //Returned first: 'New id: undefined'
return newId;
},
clearAll: function() {
$cordovaLocalNotification.clearAll();
},
setNotification: function(show) {
$ionicPlatform.ready(function() {
$cordovaLocalNotification.schedule({
id: notify.latestId(), // undefined
title: show.name + " is out today!",
firstAt: notify.alertTime()
});
});
}
};
return {
setNotification: function(show){
notify.setNotification(show);
},
clearAll: function(){
notify.clearAll()
},
setAll: function() {
console.log('Set all');
}
};
})
Not sure if this is the correct approach but it fixed my problem. I removed the latestId() method and wrapped the promise around the setNotification() code so that it doesn't try and create a notification until the promise is resolved. See below:
var notify = {
alertTime: function() {
t = new Date();
t.setSeconds(t.getSeconds() + 10);
return t;
},
clearAll: function() {
$cordovaLocalNotification.clearAll();
},
setNotification: function(show) {
$ionicPlatform.ready(function() {
$cordovaLocalNotification.getAllIds().then(function(result){
var newId = result.length;
$cordovaLocalNotification.schedule({
id: newId,
title: show.name + " is out today!",
firstAt: notify.alertTime()
});
});
});
}
};