Refreshing data in AngularJs is like pressing the reset button for

My database contains a list of customers who joined in different years. I have configured my API accordingly and it works smoothly. The issue I am facing is that when using AngularJS to pull the data with the same route (/customers/:id), it doesn't refresh automatically; it only refreshes if I manually refresh the browser. Any assistance would be highly appreciated.

HTML links

<table>    
<tr><td><a href="#customers/2014">2014</a></td></tr>
<tr><td><a href="#customers/2013">2013</a></td></tr>
<tr><td><a href="#customers/2012">2012</a></td></tr>
</table>

App.js (sample of where its called)

.when("/Archive/:param/", {
        templateUrl: "Customers/Customers.html",
        controller:"CustomersController"
    })

CustomersController

 (function () {

var CustomersController = function ($scope, customerService, $log, $routeParams, $location, $sce) {

    var param = $routeParams.param;
    var customer = function (data) {
    $scope.Customer= data;
    };

    var errorDetails = function (serviceResp) {
        $scope.Error = "Something went wrong ??";
    };

    var refresh = function () {
        customerService.customer(param)
        .then(customer, errorDetails);
    };

    refresh();


};

app.controller("CustomersController", ["$scope", "customerService", "$log", "$routeParams", "$location", "$sce", CustomersController]);
}());

CustomerService.js

    (function () {
    var customerService = function ($http, $q, $log, $scope) {
        var cachedCustomer;

        var customer = function (param) {
            var params = param;
            console.log("this is the "+params);

            if (cachedCustomer)
                return $q.when(cachedCustomer);

            return $http.get("http://localhost:8080/api/customers/year/" + params)
                        .then(function (serviceResp) {

                            $log.info(cachedCustomer);
                            cachedCustomer = serviceResp.data;
                            $log.info(cachedCustomer);
                            return serviceResp.data;
                        });
        };

        return {
            customer: customer,

        };
    };

    var module = angular.module("CustomerModule");
    module.factory("customerService", ["$http", "$q", "$log", customerService]);
}());

Answer №1

If you look at the code snippet in customerService.js on this specific line

                if (cachedCustomer)
                  return $q.when(cachedCustomer);

You are checking for a cached result and returning it if it exists. However, because the cache is set in the .then block and never removed, the $http call only occurs once due to services functioning as singleton objects. To ensure that you can access updated information, I suggest either adding a flag to customerService.customer() to bypass the cache check or modifying customerService to cache the unresolved promise rather than the data itself. Then, clear this cache once the data is obtained in your .then function. This approach prevents multiple $http calls until at least one resolves or is rejected.

Answer №2

Consider utilizing the following code snippet:

$route.reload();

Don't forget to inject $route into your controller for it to work properly.

Answer №3

Refreshing the browser clears the cached customer data and triggers a new request for information. It's important to remember to clear the cached customer data whenever you change the year parameter being passed.

One solution is to create a caching service that stores customer information based on the URL from which it's requested. Essentially, you can set up an array that acts like a hashmap, with the URL serving as the key and the information as the value. Keep in mind that this may not be ideal if your data is frequently changing on the backend.

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

Server has sent an Ajax response which needs to be inserted into a div

I have a modal window that sends a POST request to the server. Before returning to the view, I store some information in ViewData. Here's an example of what I'm doing: ViewData["Msg"] = "<div id=\"msgResponse\" class=\"success ...

show certain DIVs based on the URL

Is it possible to dynamically display different sections based on the URL? My event website has 3 subevents, and I'd like to show the date of each event in the navigation bar for their respective URLs. <div id="us" class="us-web-date">&nbs ...

"Enhancing Code Functionality in React - Seeking Ways to Improve

When working with Redux, I often find myself repeatedly using the same piece of code: const dispatch = useDispatch() Then, every time I need to call a function, I do something like this: dispatch(endpointError(true)) My goal is to streamline this proce ...

The background size cover feature is not functioning properly on mobile devices, especially on longer pages

In my Next.js project, I am encountering an issue with the background image not displaying on longer pages when viewed on a Google Pixel 3a device. Here is how it looks on shorter pages that do not exceed the viewport height: https://i.sstatic.net/jJBTy.pn ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Press the body to update state in React and close the dropdown

Seeking a solution for closing a dropdown menu when a user clicks outside of it or on another element? Consider the following code snippet written in React: var Hello = React.createClass({ getInitialState() { return { openDropdown: false ...

Utilizing Zustand state management with Next.js 13.4.12 for routing and server-side rendering, enhanced with local storage

My Zustand store code looks like this: import create from "zustand"; import { persist } from "zustand/middleware"; const useProjectStore = create( persist( (set) => ({ selectedProject: null, setSelectedProject: (pr ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

Passing Data Between Page and Component (NEXT.JS + LEAFLET Integration)

I have recently started using Next.js with Leaflet maps and have encountered a beginner's question. I created a page in Next.js ( /pages/map/[id].jsx ) that utilizes a component ( /component/Map.jsx ). Within the page ( [id].jsx ), I fetch a JSON fil ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Tips for creating a custom Angular Material modal window that is fully responsive to its parent modal window

Hey there! I've put together a custom modal window in Angular Material by combining the custom modal window example with the Angular Material slider demo. Everything is working well except for the fact that the sliders inside the modal window are not ...

The challenge of optimizing Angular websites for SEO while also addressing page reload issues

I am struggling to create SEO-friendly URLs in my Node server backend. I want URLs like the following: http://localhost:3003/my-new-mobile //product http://localhost:3003/my-new-category //category http://localhost:3003/my-first-blog-post // blog post I ...

How can we activate navigation on a mobile browser?

I am currently working on a small HTML5/JavaScript website designed to be accessed by mobile browsers on devices such as Android and iPhone. I am utilizing the geolocation feature of HTML5 to obtain the user's current location, but my goal is to then ...

Is it possible to dynamically load an npm package based on the user's browser?

My current goal is to utilize the ResizeObserver Polyfill specifically for Edge browsers. I noticed the concept of ponyfill in the npm package documentation. Would I need to develop my own ponyfill, or is there an alternative approach that could be consi ...

Assigning an argument of type `any` to a parameter of type `Observable<IComboboxItem[]>` can be considered risky

I have a piece of code that retrieves data from the backend server. Here is the code snippet: @Injectable() export class DictionariesDatasourceFacadeService { public invoiceTemplate: IDataSource<IComboboxItem>; public replacedLegalEntity: IData ...

Javascript initial keypress delay for movement in 3D space

I am aiming for a seamless movement experience when pressing a key - with the object initiating its movement upon the first press and then continuously moving while the button is held down. //setting movement speeds var xSpeed = 0.5; var zSpeed = 0.5; do ...

Changing an HTML table into an array using JavaScript

Is it possible to transform an HTML table into a JavaScript array? <table id="cartGrid"> <thead> <tr> <th>Item Description</th> <th>Qty</th> <th>Unit Price</th> ...

Head styles for tinyMCE

When viewing the tinyMCE example on the official website using Firefox, you may notice the editor blinking. This issue seems to only occur in Firefox, possibly due to external CSS files for the editor. I am considering adding all CSS rules directly into th ...