Tips for successfully implementing a then function

I'm currently working on implementing a delete service in Angular.

Below is my controller code :

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 issue arises here
        });
    };


});

and the corresponding service code:

$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;
    };

I am encountering the following error:

undefined is not a function
    at DeleteAMessage 

I realize that my function does not return a promise, but I am unsure how to rectify this. My goal is to redirect using $location.path only after the user has clicked "yes" in the modal window.

I thought about adding a "then" clause to wait for user input before initiating the redirection.

It seems like I need to create a promise, but I am uncertain of the process. Unlike with $http.get where data is expected, in this case, I just need confirmation when the user clicks "yes".

Thank you

Answer №1

Attempting to invoke .then() on a boolean value will not yield the desired result. The AngularJS documentation provides clear and simple examples illustrating the use of $q, which is Angular's implementation of promises.

As stated in the documentation:

// In this hypothetical scenario, let’s imagine that variables `$q` and `okToGreet`
// are accessible within the current lexical scope (whether injected or passed as arguments).

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('Preparing to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Unable to greet ' + name + '.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failure: ' + reason);
}, function(update) {
  alert('Notification received: ' + update);
});

Answer №2

If you want to enhance the functionality, simply include a callback function parameter in your code.

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

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

Answer №3

If you want to implement promise in your script using the $q service, here is how you can do it:

$this.DeleteMessage = function(message){
        //var status = true;//no longer necessary
        var defer = $q.defer(); //inject $q into your service using dependency injection - this creates 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
                };

                // show the modal box
                modalYesNoService.showModal({}, modalOptions).then(function (result) {              

                    var index = _.indexOf(messageList, _.find(messageList, function (_message) { return _message._id == message._id; }));
                    $this.DeleteMessageFromServer(message).then(function(promise){
                        messageList[index]._id = 0;
                        defer.resolve({message:"Message successfully deleted"});
                    },function(){//this is the error callback if you used $http for DeleteMessageFromServer
                        defer.reject({error:"An error occurred while deleting the message"});
                    });
                });
            });
        }
        else{
            defer.reject({error:"No message specified"});//this will trigger the error callback of the promise
        }
        return defer.promise;//return a promise on which you can use .then()
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a popup using JavaScript in an ASP.NET page can be challenging when it comes to passing values

The list page in my parent window displays multiple rows, each representing an individual person. Next to each person's name is an icon that links to the "change status" page. When clicking on the icon, a popup page should open where the status of th ...

What is the best method to transfer information from a What You See Is What You Get editor to a database using Vue.js?

I have recently started using the Vue2Editor in order to streamline my process of sending text and image data to my Firebase database. However, I am encountering an issue where the entered data is not being added successfully. Previously, with traditional ...

The issue of AngularJS $http.get not functioning properly with a jsp page has arisen due to its simplicity

1 / I developed a myPage.jsp page within an eclipse project named erixx : <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE> <html><head></head> <body> <% String aa ...

Using AngularJS to incorporate JSON data into a static page without any predefined template

On my static page full of articles, I am interested in populating the number of likes for each article from a JSON file using AngularJS. Is this achievable, or do I have to load the entire page as a template and fill in all the details with ng-repeat? Is ...

Handling the android back button in a react native application

On screen A, I have a dropdown with its default state set. When a new value is selected from the dropdown, the state updates and navigates to a new screen with data based on the updated state. In the new screen, there is a back button in the header as well ...

The issue of integrating jQuery with the textarea CKEditor is still unresolved

I'm having an issue with applying the ckeditor function to append data in my code. I have included a cdn link for ckeditor in the header.php file, but it's not working as expected. How can I resolve this? <script> $(document).ready(func ...

Unveiling the Magic: Transforming Objects into HTML Attributes using AngularJS

I have been working on developing a highly dynamic ng directive that creates tables based on a given data array and configuration object. I am looking for a way to assign attributes dynamically based on an object within the scope. For example, if I have an ...

Determining Whether a Specific Value Exists in the JQuery Selector '.name'

Is there a way to check if a specific value exists within the elements with the class of $('.name')? I'm already looping through an array to look for each entry in $('.name'), so I can't iterate over $('.name') as we ...

Assign an identifier to the HTML helper Html.EditorFor

When using a textbox created with the HTML helper "@Html.EditorFor", there may be a need to perform some action with JavaScript on its change event. In order to do this, an ID needs to be set for the textbox. For example, if you need to set a string value ...

What role does the css-loader play in webpack?

As I dive into Webpack 2, I've noticed that many projects utilize the css-loader, but I'm unsure of its exact purpose. ...

The change() function isn't being called in the FooterControl of the nested Gridview

In my gridview, there is a nested structure with a footer row for inserting data. When the parent row expands, the footer controls are generated. There are two dropdowns where the second dropdown's options depend on the selection in the first dropdown ...

The process of automating e-signature input with Selenium

Is there a way to automate e-signature input in Selenium? I attempted using the action class to draw a line on the canvas object. Below is the code I used: Actions actionBuilder=new Actions(driver); Action drawOnCanvas=actionBuilder ...

Add a sound file to the server and configure the images based on the server's response

I am a newcomer to JavaScript and AJAX, and I am facing an issue while trying to upload an audio file to the server and display the image from the server response. When attempting to pass the audio file from the input tag to an AJAX call, I encounter an il ...

obtain a jQuery element from a function

Can a function return a $ object, or does it need to be converted to a string before being returned? function returnObj() { obj = $("<img id='' src='' />"); return obj; } var obj = returnObj(); alert(obj); //returns [obj ...

Troubleshooting problem with Zscaler and Ajax communication

When making an AJAX call on my website, everything runs smoothly except for when it is accessed behind a Zscaler proxy. In that case, the browser throws a CORS error: "No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

Fill an HTML div with JSON data obtained from a server

I am trying to display JSON data from a json-rpc server inside an HTML div. I can see the data in Chrome and Firefox dev tools, but I need it to be displayed within a specific div on the page. I have written a script to populate the 'mybox' div, ...

What are the steps to rearrange the order of states in ui-router?

I'm facing a situation where I need to reorder a list, but as someone new to ui-router, I'm struggling to figure out how to achieve this. My state configuration looks like this (including resolve to pass the data): $stateProvider .state(&ap ...

The utilization of useEffect causes the page to go blank

Essentially, the issue is that once I include useEffect(() => { const fetchData = async () => { const result = await fetch('http://localhost.com/ping'); console.log(result) }; fetchData(); }, []); in my compone ...

Learn the process of extracting query parameters from a URL with the format `example.com/path#p1=v1&p2=v2...` using Angular

Callback URLs from singly.com are coming in the format of example.com/path#p1=v1&p2=v2... Is there a more Angular-friendly way to extract query parameters since $location.search and $routeParams do not work without the presence of the ? in the URL? ...

What steps should I take to resolve the issue of 'this.reduce() not being a function'?

Here is my code : app.get("/", (req, res) => { const reducer = (acc, guildCount) => acc + guildCount; const results = client.shard.fetchClientValues('guilds.cache.size'); console.log(results) let guildCount ...