Home > OS >  How to return a closure or handle not returning a closure
How to return a closure or handle not returning a closure

Time:06-09

I am new to angular and I am working on a project in my company where I have to implement a delete function.

I have manage to implement the function where user goes ahead with the deletion. But if he changes his mind in the last minute and cancel the delete confirmation, I am getting an error.

Here is my code:

$scope.deleteButtonClick = function () {
                
    if ($scope.hasRemove()) {
        $scope.deleting = true;
        //Fetch the promise and add our own state management to it
        var promise = $scope.removeAction(); // this remove action calls the below 'remove' function
        if (!promise.then) {
            throw "Wizard's bound 'deleteAction' must return a closure."
        }
        promise.then(function () {
            $scope.deleting = false;
        }, function () {
            $scope.deleting = false;
        });
    }
};

Following is the remove function where I want to return a closure.

$scope.remove = function () {

    if (confirm("Confirm Delete?")){

        var data = {};

        data.id = EventService.event.id;

        // delete
        return $http.post('/admin/deleteAjax/', data).then(
              function (response) {
                        
                 if (response.data.status == 'success') {
                     RegistryService.getItem("successModal").show();

                     setTimeout(()=>{
                           location.replace("/admin/index")
                     }, 2000);
                  }
                  else if (response.data.status == 'error'){
                       RegistryService.getItem("errorModal").show();
                  }
               }
          );
        }
        else {
           // This is where I need to return a closure
           // when user presses 'cancel' button how can I return a closure or skip the error?
        }
    };

Following is the error I am getting when I return false in the else section.

Wizard's bound 'deleteAction' must return a closure. undefined

Does anyone have an idea how to fix this issue?

CodePudding user response:

The problem is that $scope.remove() needs to return a Promise, and the else clause in the confirm() block is not returning a Promise.

To do that, you can use the AngularJS $q service to create a Promise and return it.

So your else block would look like this:

} else {
  // This is where I need to return a closure
  // when user presses 'cancel' button how can I return a closure or skip the error?
  const deferred = $q.defer(); // <------------ use $q service to create a deferred
  deferred.resolve({ cancelled: true }); // <-- resolve it to whatever value you want
  return deferred.promise; // <---------------- and return its promise
}

Here's a fiddle showing this approach.

  • Related