Tips for canceling an http request in angularjs when the requesting controller has exited its scope

Developed a custom angularjs application with ng-view for loading four different modules using route provider. Each module makes HTTP requests as shown below:

var requestManager = {
    "locations": {},
    "employees": {},
    "items": {},
    "templates": {}
};
sendRequestToServer = function (reqObj) {
    var reqObj = reqObj,
        httpObj = {},
        defer = $q.defer();
    httpObj = {
        method: reqObj.method,
        url: baseUrl + reqObj.url,
        timeout: 90000
    };
    if (reqObj.method == 'GET') {
        httpObj['params'] = reqObj.data;
        if (reqObj.uniqueId) {
            httpObj['headers'] = {
                'uniqueId': uniqueId
            }
        }
    } else if (reqObj.method == 'POST' || reqObj.method == 'PUT') {
        httpObj['headers'] = {
            'Content-Type': 'application/x-www-form-urlencoded'
        };
        httpObj['data'] = reqObj.data;
    }
    requestManager[reqObj.moduleName][reqObj.requestName] = $http(httpObj).success(function (data, status, headers, config) {
        var dataObj = {
            data: data,
            status: status,
            headers: headers,
            config: config
        };
        defer.resolve(dataObj);
    })
        .error(function (data, status, headers, config) {
            var dataObj = {
                data: data,
                status: status,
                headers: headers,
                config: config
            };
            defer.reject(dataObj);
        });
    return defer.promise;
}

Looking to improve the functionality where on changing routes from one module to another aborts any ongoing server communication requests. Attempting to handle this by listening for destroy event:

$rootScope.$on('destroyModule', function(event, moduleName) {

    var requests = requestManager[moduleName]
        , defer = $q.defer()
        , index
        , req;
    for(req in requests){

    //Want to abort the request
        defer.reject(requests[req]);

    }
})

Encountering issues with the above approach. Seeking guidance and advice on how to achieve the desired behavior. Thank you!

Answer №1

When it comes to the $rootScope, the destroy event will not be triggered. However, you can listen for it on another scope, such as in a views controller:

$scope.$on("$destroy", function(){ ... });

If you are looking to detect location changes specifically, you can achieve that like so:

$rootScope.$on("$locationChangeStart", function(){ ... });

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

The Angular HTTP interceptor response function filters out the message parameter from the server's response

In my application, all server responses follow a structured format: response = { data: {}, status: STATUS_CODE, message: STRING_MESSAGE } I am exploring the use of Angular's HTTP response function to showcase specific response messages i ...

Tips on avoiding a page reload following a form submission using JQuery

Currently developing a website for my app development project, I've encountered an unusual issue. Utilizing some JQuery to transfer form data to a php page called 'process.php' and then add it to my database. The strange part is that the pa ...

Display of undefined data in Ajax success response

After receiving an array object data in the Ajax success result, I am trying to print li tags but they are showing as undefined. This is my Ajax code: $.ajax({ 'method': 'GET', 'url': base_url +'party/sel ...

Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank. The SELECT queries in use are as follows: -- Retrieve all users S ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...

The printing code is not able to interpret the CSS

Having trouble with this script not reading the style properly when printing, can anyone assist in identifying the issue? <script type="text/javascript"> $(function () { $("#btnPrint").click(function () { var contents = $( ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

It appears that the collection.add() method in connector/node.js only successfully executes one time

Currently, I am experimenting with MySQL Document Store to compare it with our relational tables. To achieve this comparison, I am working on transforming our existing table into a collection. The table contains approximately 320K records that I need to ...

Adjust the contents of an HTTP POST request body (post parameter) upon activation of the specified POST request

Is there a way to intercept and modify an HTTP Post Request using jQuery or JavaScript before sending it? If so, how can this be achieved? Thank you. ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

The issue of sluggishness in Material-UI when expanding the menu is causing delays

Watch Video Having trouble with the behavior of the Menu opening and closing similar to this example. The text seems slow to change position. Any ideas why? This is the devDependencies configuration I am using in webpack. "devDependencies": { ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

Mastering the Art of Utilizing AngularJS to Harness the Power of Keypress and

Currently, I am in the process of developing a calculator utilizing AngularJS. The issue arises when clicking on the '923216' buttons triggers the "updateOutput(btn)" function, successfully appending them and updating the view. However, upon addi ...

NavigateToTop/BackToTheBeginning

I'm facing a challenge with a page layout that involves two vertical div's - one for the menu on the left and another for loading content on the right. My goal is to utilize the .scrollintoview() function on the menu div so that when a link is cl ...

Troubleshooting problem with decrypting data using CryptoJS AES256

I am currently facing an issue with the decryption of a URL that has been encoded using AES256. I am using CryptoJS for the decryption process, but I keep encountering the following exception: Malformed UTF-8 data Have I missed something in the code? rout ...

React: Show input value on button click

I have been working on a React form that displays the entered input value in a controlled input element only after the user hits the submit button, rather than updating it constantly as the user types. Here is my current solution using conditional renderin ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

Encountering an issue while attempting to test geolocation functionality in the web browser

I've been working on integrating the geolocation API into my app and came across a suitable resource at the MDN website. However, when I attempted to test for the existence of the geolocation object in the browser, I encountered this error: Server Err ...

Whenever a menu option is clicked in Umbraco, the page always redirects to the route #/content

After updating my site to the latest version available, I encountered a problem: Whenever I click on any link in the menu on the admin page (/umbraco) The temporary solution I discovered is Click on the link Go to profile Edit Confirm that you want to ...