我正在尝试使用 angular 创建删除服务。
这是我的 Controller :
app.controller('VoirMessagesController', function($scope, $rootScope, $routeParams, $location,$translate, userService, dataRefreshServices){
$scope.messageToWatch = dataRefreshServices.getMessageToWatch();
this.DeleteAMessage = function(){
dataRefreshServices.SupprimerMessage($scope.messageToWatch).then(function(){
$location.path('/messages'); // The problem is here
});
};
});
服务调用:
$this.SupprimerMessage = function(message){
var retour = true;
if(message != undefined)
{
$translate(['MESSAGES_MESSAGERIE_SUPPRIMER', 'BUTTON_CANCEL', 'MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TEXTE', 'MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TITRE']).then(function(translations)
{
var modalOptions = {
closeButtonText: translations.BUTTON_CANCEL,
actionButtonText: translations.MESSAGES_MESSAGERIE_SUPPRIMER,
headerText: translations.MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TITRE,
bodyText: translations.MESSAGES_MESSAGERIE_MESSAGE_VALIDATION_SUPPRESSION_TEXTE
};
// displaying the modal box
modalYesNoService.showModal({}, modalOptions).then(function (result) {
var index = _.indexOf(listeMessages, _.find(listeMessages, function (_message) { return _message._id == message._id; }));
$this.SupprimerMessageFromServer(message).then(function(promise){
listeMessages[index]._id = 0;
});
});
});
}
return retour;
};
我得到错误:
undefined is not a function
at DeleteAMessage
我知道我的函数不返回任何 promise ,但我不知道如何才能完成这项工作,我只想在用户在我的模态窗口中单击"is"时使用 $location.path 完成重定向.
我想添加一个“then”来等待用户的回答,然后再进行重定向。
看起来我应该创建一个 promise ,但不知道如何“创建”一个 promise 。当我使用 $http.get 时,我了解 promise 中的内容,但在这里我不能(在没有预期数据之前,我只想知道用户何时单击是)。
谢谢
最佳答案
您正在尝试对 bool 调用 .then()
,这当然是行不通的。 AngularJS documentation包括关于使用 $q(它的 promise 风格)的非常容易理解的示例。
来自文档:
// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function() {
deferred.notify('About to greet ' + name + '.');
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deferred.promise;
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
}, function(update) {
alert('Got notification: ' + update);
});
关于javascript - 如何使 then 函数工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606717/