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

Show various error messages depending on the type of error detected

When pulling data from an API, my goal is to handle errors appropriately by displaying custom error messages based on the type of error that occurs. If the response is not okay, I want to throw an error and show its message. However, if there is a network ...

Utilizing the Google Maps API to geocode addresses and postponing the retrieval of the data

Utilizing Google's maps API to geocode two addresses has brought about a unique challenge for me. I am deferring the returned results and utilizing a $.when().then() method to execute my logic once I receive the coordinates for the string addresses. T ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

What is the syntax for accessing a dictionary item within a <span> tag using JavaScript?

I'm working on a new functionality for a website that involves using a dictionary to store information about clubs, events, and times. var clubName = {}; var event = {}; var time = {}; var dict = new Map(); dict.set(clubName, "G ...

Troubleshooting: Issue with Jquery functionality when selecting an item from dropdown menu

I've been trying to dynamically select an item from a dropdown menu, but for some reason it's not working even though I've followed the suggestions on this forum. Here is my HTML: <div> <div class="form-group"> <la ...

Leveraging dynamic visuals for your Twitter metadata image

My Twitter application automatically posts the current title being broadcast on my web radio every 20 minutes. It includes details like the artist, number of listeners, and playlist, but does not display album covers. To work around this limitation, I am ...

Troubleshooting SQLite Query Problems in Flask

I'm currently developing an API using Flask, and I have implemented an HTTP DELETE method that is responsible for deleting records in SQLite based on the ID provided as a JSON input. In case the specified ID does not exist in the database, no error o ...

Utilize a function on specific attribute values

I have a function in JavaScript that is designed to convert all relative URLs into absolute URLs. function rel2Abs(_relPath, _base); //_relPath represents the relative path //_base indicates the base URL Now, my objective is to implement this function on ...

Conducting simultaneous tests on the mobile application and web browser to ensure optimal performance

Dear friends, I am in need of some assistance. I am looking to run end-to-end tests simultaneously on a mobile app and a web browser, make alterations on one platform, and check to see the changes reflected on the other multiple times. My current plan is t ...

Storing Radio Buttons and Checkboxes Using LocalStorage: A Simple Guide

Is there a way to save and retrieve values from localStorage for input types "radio" and "checkbox"? I've tried using the same code that works for text and select elements, but it doesn't seem to be saving the values for radio and checkbox. Can s ...

Sending an object and array using an Angularjs service: An easy step-by-step guide

I encountered an issue while attempting to send both an object and an array to an API simultaneously. Here is the object data from input boxes: var vacation = { Vac_Main_Key: $scope.vackey, Vac_Main_Code: $scope.code, Gender_Type: $scope.gen ...

Resizing a scrollable list using React Refs and UseLayoutEffect

Essentially, my issue stems from having a scrollable list with a set maximum height of '100vh'. I also have a detail card beside the list that contains accordion components. When one of these accordions is expanded, it increases the height of the ...

Simple method for converting pixel values to em units

I'm searching for a simple method to incorporate a line of code into one of my plugins in order to convert specific pixel values into em values. My project's layout requires the use of ems, and I'd prefer not to rely on external plugins for ...

D3.js: Unveiling the Extraordinary Tales

I'm currently working on a project that requires me to develop a unique legend featuring two text values. While I have successfully created a legend and other components, I am facing difficulties in achieving the desired design. Specifically, the cur ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Setting up a Node.js Web Server Installation

I recently purchased a book on Angular JS called "Pro Angular JS" and I'm facing some difficulties in setting up a web server to the correct port. When I try to install connect using Node, I encounter an error message stating: npm should be run outsi ...

Incorporate a div beside a button using componentDidMount in a React component

Upon page load, I aim to position an info icon div next to a button node. However, the button node is not available when componentDidMount is triggered. I have attempted to use setTimeout, but its effectiveness varies depending on the amount of data in th ...

Twice the clicking actions triggered by the event

Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice. HTML <label class="label_one"> Label One <input type="checkbox"/> </label> However, if I modify the HTML code as f ...

AngularJS routing to a specific view

Here is some code snippet you may find helpful: This code will render the /result content every time the defaultview function is called using the $route service: angular.module('myapp').controller ('ResultController',['$route ...

Why is it that consolidating all my jQuery plugins into one file is ineffective?

Prior to this, I included the following scripts: <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/json2.js"></script> <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/jquery-msdropdown/js/jquery.dd.js"></script&g ...