我在使用异步功能时遇到了这个问题。关键是“执行”不等待NotificationService.confirm
回调的返回。
我的意思是,这显示了一个PhoneGap警报,但它并不等待评估按下哪个按钮的用户。因此,您可以在控制台中看到输出,undefined
而不是false / true / 3值
[编辑]
这是Maxim Shoutin提出的代码,但尚无法正常工作:
NotificationController.js
angular.module('app').controller("NotificationController", function($rootScope) {
$rootScope.cancel_button = function() {
var confirm = NotificationService.confirm("Do you want to confirm?", 'Yes!');
confirm.then(function(result) {
console.log('Confirm: ' + result);
if(confirm) $location.path('/menu');
}, function(result) {
console.log('No data returned');
})
}
/* Additional controller code... */
}
NotificationService.js
angular.module('app').factory("NotificationService", function() {
// Callback function
var onConfirm = function(button) {
console.log('Callback function called!!!');
if(button == 1) return false;
else if(button == 2) return true;
else if(button == 3) return 3;
else return false; // dismissed without press button
};
return {
confirm : function(alert_msg, title, buttonsArray) {
var deferred = $q.defer();
if(buttonsArray == null) {
buttonsArray = ['Cancel', 'OK'];
}
var data = navigator.notification.confirm(
alert_msg, // message
onConfirm, // callback
title, // title
buttonsArray // buttonsArray
);
deferred.resolve(data);
return deferred.promise;
}
}
}
控制台输出
> Confirm: undefined
(在用户按下按钮之前)
> Callback function called!!!
(AFTER用户按压按钮)
问题是NotificationService.confirm("Do you want to confirm?", 'Yes!');
返回承诺(ae异步)。
所以应该是这样的:
var confirm = NotificationService.confirm("Do you want to confirm?", 'Yes!');
// now confirm is a promise
confirm.then(function (result) {
console.log('Confirm: ' + confirm);
if(confirm) $location.path('/round/actual');
}, function (result) {
alert("Error: No data returned");
})
仅用于演示,我们可以$timeout
用来模拟异步调用:
app.factory('NotificationService', function($q,$timeout) {
// Callback function
var onConfirm = function(button) {
var state;
console.log('Callback function called!!!');
if(button == 1) state = 'working!';
else state = false; // dismissed without press button
return state;
};
var factory = {
confirm : function(alert_msg, title, buttonsArray) {
var deferred = $q.defer();
$timeout(function () {
var state = onConfirm(1); // simulate call callback after 3 sec
deferred.resolve(state);
}, 3000);
return deferred.promise;
}
}
return factory;
});
演示版 Plunker
在您的情况下,由于navigator.notification.confirm
使用了回调,因此您可以尝试从回调中返回解析。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句