Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使then函数工作?_Javascript_Angularjs - Fatal编程技术网

Javascript 如何使then函数工作?

Javascript 如何使then函数工作?,javascript,angularjs,Javascript,Angularjs,我正在尝试使用angular创建一个删除服务 这是我的控制器: app.controller('VoirMessagesController', function($scope, $rootScope, $routeParams, $location,$translate, userService, dataRefreshServices){ $scope.messageToWatch = dataRefreshServices.getMessageToWatch(); th

我正在尝试使用angular创建一个删除服务

这是我的控制器:

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 
我知道我的函数不会返回任何承诺,但我不知道如何才能做到这一点,我只希望在用户在我的模式窗口中单击“是”时,使用$location.path进行重定向

我想添加一个链接,然后在执行重定向之前等待用户的回答

看起来我应该创造一个承诺,但我不知道如何才能创造一个承诺。当我使用$http.get时,我理解承诺中的内容,但在没有预期数据之前,我无法理解,我只想知道用户何时单击了“是”

谢谢你

你想打电话。然后是电话,当然不行了。其中包括非常容易理解的关于使用$q的例子,以及它的承诺风格

从文档中:

// 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);
});
你想打电话,然后打电话,这当然行不通。其中包括非常容易理解的关于使用$q的例子,以及它的承诺风格

从文档中:

// 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);
});

以下是如何在脚本中介绍promise with$q服务:

$this.SupprimerMessage = function(message){
        //var retour = true;//no more need
        var defer = $q.defer(); //inject $q into your service via dependency injection - here create a promise
        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;
                        defer.resolve({message:"Message corectly deleted"});
                    },function(){//this is the error callback if you used $http for SupprimerMessageFromServer
                        defer.reject({error:"Something went wrong while deleting message"});
                    });
                });
            });
        }
        else{
            defer.reject({error:"No message defined"});//this will go to the error callback of the promise
        }
        return defer.promise;//whatever return a promise on which you'll be able to call .then()
    };

以下是如何在脚本中介绍promise with$q服务:

$this.SupprimerMessage = function(message){
        //var retour = true;//no more need
        var defer = $q.defer(); //inject $q into your service via dependency injection - here create a promise
        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;
                        defer.resolve({message:"Message corectly deleted"});
                    },function(){//this is the error callback if you used $http for SupprimerMessageFromServer
                        defer.reject({error:"Something went wrong while deleting message"});
                    });
                });
            });
        }
        else{
            defer.reject({error:"No message defined"});//this will go to the error callback of the promise
        }
        return defer.promise;//whatever return a promise on which you'll be able to call .then()
    };

只需为回调添加一个参数函数类型

$this.SupprimerMessage = function(message, callback){
....
/* user pressed ok */
listeMessages[index]._id = 0;
callback();
....
}

$this.DeleteAMessage = function(){
    dataRefreshServices.SupprimerMessage($scope.messageToWatch, function() {
        $location.path('/messages');        
    });
};

只需为回调添加一个参数函数类型

$this.SupprimerMessage = function(message, callback){
....
/* user pressed ok */
listeMessages[index]._id = 0;
callback();
....
}

$this.DeleteAMessage = function(){
    dataRefreshServices.SupprimerMessage($scope.messageToWatch, function() {
        $location.path('/messages');        
    });
};