Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table.

Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I navigate back to the listing page after a route change, the ajax call is triggered again. What I would like to achieve is to store the expense object during the initial ajax call and reference the same object until manual browser refresh occurs.

If you can provide assistance in achieving this goal, here is the factory code snippet below. My preference would be to use this.expenses if the data is already present.

admin.factory('expenseFact', ['$http', function($http) {
    var expense = {};

    this.expenses = "";

    expense.getExpenseList = function() {
        this.expenses = $http({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            method: "GET",
            url: base_url + "rest/expenses"
        });

        return this.expenses;
    };

    return expense;
}]);

Additionally, here is my controller code for reference:

admin.controller('expenseLandCtrl', function ($scope,$rootScope,expenseFact) {
    $scope.pageTitle = $rootScope.pageTitle;

    expenseFact.getExpenseList().then(function (data) {
        $scope.expenses = data.data;
    });

});

admin.controller('expenseAddCtrl', function ($scope,$rootScope,expenseFact) {
    $scope.pageTitle = $rootScope.pageTitle;
});

Answer №1

your factory will resemble the following structure:

    admin.factory('expenseFact', ['$http', function($http) {
    return {
        getExpenseList: function() {
            var expense = {};
            this.expenses = $http({
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                method: "GET",
                url: base_url + "rest/expenses"
            });

            return this.expenses;
        }
    }
}]);

you can then call it from the controller in a similar manner without it being called automatically. By the way, I recommend utilizing promises.

below is the same code modified to use promises:

admin.factory('expenseFact', ['$http', '$q'. function($http, $q) {
    return {
        getExpenseList: function(){
            var deferred = $q.defer();
            $http({method: 'GET', 
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
                }).
            then(function(response) {
                deferred.resolve(response.data);
            }, function(response) {
                deferred.reject(response.status)
            });

            return deferred.promise;
        }
    }
}]);

Answer №2

Ensure that you retrieve the expenses when the factory is first loaded;

admin.factory('expenseFact', ['$http', function($http) {
    var expenses = null;
    $http({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            method: "GET",
            url: base_url + "rest/expenses"
    }).success(function (exp) {
        expenses = exp;
    }); // fetch the expenses on initial factory load

    return {expenses: expenses};
}]);

This setup ensures that the expenses returned from the factory corresponds to a single ajax call for retrieving expenses.

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

Injecting dynamic variables into JSON objects using JavaScript

I am facing a challenge with populating values dynamically from an array of elements. Below is the primary array that I am working with. list = [{name: 'm1'}, {name: 'm2'},{name: 'm3'},{name: 'm4'},{name: 'm5&ap ...

Manipulate images in real-time and insert custom text using JavaScript/jQuery

Within my possession is an image depicted above. My objective revolves around dynamically altering the values present at the occurrences of L, A, and B; to achieve this, I must eliminate or conceal L, A, and B while substituting them with numerical equiv ...

Please input new items by clicking a button

I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

Unexpected null value from Ajax Form upon uploading CSV file

The setup for this functionality involves: A View where a CSV file can be uploaded A Controller Partial View Action that is responsible for parsing the CSV file, reading the objects, and passing them back to the Partial View The Partial View s ...

conceal the .card-body element if the children have the CSS property "display:none"

My challenge involves managing two collapsible cards on a webpage. I am looking for a solution where the .card-body will have its display set to none when there are no inner divs to show in the card upon clicking a letter in the pagination. Otherwise, the ...

Generate dynamic routes in Next.js only when needed

I'm currently working on a project using NextJS to create a frontend for a database that contains thousands of products, with the expectation of significant growth. The site/products/ route is functioning well, but I wanted to add a route to view indi ...

JavaScript: Extending a class with an invalid or null value is not permitted

Trying my hand at constructing a page object for login testing with WebdriverIO. Encountering the error ERROR: Class extends value #<Page> is not a function or null on line 3 of login.page.js. No clue what mistake I'm making... Is there a wron ...

Error code ENOSELF was encountered while trying to install angular-notification-icons using npm

Currently, I am utilizing the following link as a guide to construct a Notification system: https://github.com/jacob-meacham/angular-notification-icons The initial step involves executing: npm install angular-notification-icons --save I'm uncerta ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Encoding JSON and parsing data in case no results are retrieved

I am working on an AJAX project using PHP and JQuery, but I have encountered a problem. Specifically, I am facing an issue related to the dataType:"json" parameter in my Javascript code. Everything runs smoothly when the json_encode function returns rec ...

AngularJS routing is disrupted by html5mode

Encountering a unique issue while using html5Mode with ngRoute. Here is the relevant snippet of code: (function () { var config = function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'h ...

Tips for saving a web page using Selenium Webdriver in JavaScript

Is there a way to programmatically save an entire webpage using Selenium Webdriver JS in Firefox? I have been able to bring up the Save As dialog with the following code: driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + &ap ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

EaselJS: Enhancing Performance and Aesthetics with Over 200 Vector Shapes

When comparing EaselJS performance with Canvas native methods, I noticed a significant difference: 2.2 s vs 0.01 s (despite EaselJS mapping canvas native methods). I created a canvas application that draws a tree*. For animating the growth of the tree, us ...

What is the best method for transferring data within the play framework?

As a beginner in the play framework, I am looking to create a single page application. After installing the play activator and creating a play-java project, I imported the project into eclipse. I then placed my login.html and necessary js files (index.js, ...

Tips for effectively utilizing v-model and v-select in a dynamic manner

Is it possible to have a group of select elements in Vue.js that work independently with v-model without needing separate data properties for each one? For example, select 1 and select 2 should be treated as one group, while select 3 and select 4 are anot ...

Using ReactJS to create a Stacked Bar chart

I am encountering some challenges while trying to create a single stacked bar graph using data from an API. 1- The data I receive is not rounded, even when using % values. 2- Additionally, the total percentage does not always add up to 100%, causing the ...