Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing.

When accessing /berlinerliste/, a function is triggered to display an array of objects.

If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object.

The issue arises when the individual object with the URL /berlinerliste/{id}/ is reloaded, resulting in a page without data.

This is how the service is structured:

.factory('SearchService', ['$http', function($http) {

  var service = {

    flatexhibitors : [],
    datafairs : [],
    flatexhibitorsuni : [],
    datafairsuni : [],

    getAllExhibitors : function () { //initial call to fetch all items on page load
        var searchindex = 'XX';
        var url = '../getexhibitors.php';
        var config = {
            params: {
                search: searchindex
            },
            cache:true
        };
        $http.get(url, config).then(function (data) {
          service.datafairs = data.data.rows;
          for (var i in service.datafairs) {
            service.flatexhibitors.push(service.datafairs[i].doc);
          };
          return service.flatexhibitors;
        });
    },

    getAllPeople: function() { //call to reload data and filter it 
      var searchindex = 'XX';
      var url = '../getexhibitors.php';
      var config = {
          params: {
              search: searchindex
          },
          cache:true
      };
      return $http.get(url, config).then(function (resp) {
        service.datafairsuni = resp.data.rows;
        for (var i in service.datafairs) {
          service.flatexhibitorsuni.push(service.datafairs[i].doc);
        };
        return service.flatexhibitorsuni;
        console.log(service.flatexhibitorsuni);
      });
    },

    findExh : function(id){
      function personMatchesParam(exhibitor) {
        return exhibitor.slug === id;
        console.log(exhibitor.slug);
      }
      return service.getAllPeople().then(function (data) {
        return data.find(personMatchesParam)
      });

    }
  }

  service.getAllExhibitors();

  return service;

}])

This is the configuration of my views:

.config(function($stateProvider) {

  var berlinerState = {
    name: 'berliner',
    url: '/berlinerliste/',
    views: {
      'header': {   
        templateUrl: 'header.htm'   
      },
      'main':{    
        templateUrl: 'bl2017.htm'    
      }
    }
  }

  var exhibitorState = { 
    name: 'exhibitor', 
    url: '/berlinerliste/{id}', 
    views: {
      'header': {   
        templateUrl: 'header.htm'  
      },
      'main':{    
        templateUrl: 'exhibitor.htm'    
      }
    },
    resolve: {
      exhibitor: function(SearchService, $stateParams) {
        return SearchService.findExh($stateParams.id);
      }
    }
  }

  $stateProvider.state(berlinerState);
  $stateProvider.state(exhibitorState);
})

Despite the issue with the reload not functioning properly at /berlinerliste/{id}/, it also impacts the speed by making redundant HTTP calls and filtering processes. Any tips on resolving this?

  • Making duplicate HTTP calls (unnecessary if not reloading the page)
  • Filtering items based on ID
  • Correctly displaying the results from /berlinerliste/ but showing nothing upon reload

I believe ideally, the redundant HTTP call and the resolve process should only occur during a page reload, not when navigating from the parent URL. What am I missing?

You can view the live version here

UPDATE

Check out the Plunkr example from the UI Router developers where they successfully implement what I'm attempting. It works for them but not for me.

Answer №1

When you refresh the page, it's like starting your application from scratch. In a single-page application, this means losing all data because everything will be reloaded. You'll need to retrieve the data from the server again or store it in the browser's local storage. One solution is to extract the id from the URL and update your API call to the specific child route instead of the parent route like this: #!/berlinerliste/{id}.

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

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Out of Sync Promise Chain

I recently encountered an issue with promise chaining in JavaScript, specifically while working with Vue.js. Here is my code: I have an addItem function that inserts an item into the database. My goal is for this function to first insert the data into the ...

The search feature in my React Pagination is not performing as effectively as expected

I recently set up a React app that interacts with a MongoDB database using an Express Server. The pagination feature is working smoothly, but I encountered an issue with the search function. It only works when typing in the input box; deleting characters d ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

Issue encountered where Moment locale functionality is working in local development environment, but not functioning properly in the

My application built with Next.js requires displaying the date in Bengali instead of English. The issue arises after running the build command 'build:next build' where the production version displays the date in English (e.g. '20 January, Su ...

Text parsing with jQuery

Hello fellow developers. I am interested in creating a text parser using jQuery. My goal is to develop a function that can take a string as input and convert it accordingly. Imagine we have a div with the following HTML structure: <div class="item"> ...

Unable to successfully add element to array using UIKit modal in vuejs

On my webpage, I have a table that showcases an array of "currency" objects: <tbody> <tr v-for="currency in currencies" v-bind:key="currency.Name"> <td class="uk-width-medium">{{currency.Enabled}}</ ...

Image-switching button

I'm new to JavaScript and struggling with my first code. I've been staring at it for two days now, but can't figure out what's wrong. The goal is to create an HTML page where the user can change an image by clicking on a button, and th ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Using JavaScript to reduce, group, and sum nested objects

I'm a third-year student working on my first internship project and struggling with organizing and aggregating data from a JSON object. The goal is to group the data by name, calculate total weight per name, and sum up the grades for each entry. I&apo ...

Create a PHP file with various functions and access them using jquery.post or jquery.get in a separate JavaScript file

Is there a way to call multiple PHP functions from my JavaScript file using Jquery.post? Typically, we use Jquery.post to call a PHP file and pass various values as post data. function new_user(auth_type, tr_id, user_name, email) { $.post("bookmark.p ...

Tips for modifying the max length value in Angular

I'm just starting out with Angular and I'm trying to alter the maxlength property from 300 to 140 upon clicking a button. The buttons are generated using ng-repeat and only the first one should change the value to 140, while the others should rem ...

Subdomain for an Ajax request

Can we use ajax requests to extract data from and fetch information from pages like ? It appears that JavaScript still does not permit subdomain requests. ...

The value of a select box cannot be retrieved until it has been clicked on

I am working with a selectBox element in my code: <select class="span2" name="filterYear" id="filterYear" style="margin-right:10px;"> <% for (var i = 0; i < years.length; i++) { %> <% if (years[i] == selectedYear) { %> ...

Understanding the process of retrieving a data value from HTML in an AngularJS directive

I'm a beginner with Angular and I'm trying to pass some data to my angular directive from the template. <div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div> I h ...

How can I unselect a radio button by double clicking on it?

I am in need of a specific feature: When a user clicks on a radio button that is already checked, I want it to become unchecked. I've attempted to implement this code but unfortunately, it has not been successful. $(document).on('mouseup' ...

Comparing response times between AngularJS $http and $.ajax callbacks

I am puzzled as to why AngularJS $http service's success callback is giving me a slower response time compared to the $.ajax success callback. I ran this code 5 times with different JSON files: if(isJquery){ $.ajax({ type : 'GET', ...

Leverage JSON data to generate individual elements, rows, and columns for every object within the array

Just starting out with JavaScript and struggling a bit. We need to fetch data from this URL: and then manipulate the data to create new rows (tr) and columns (td) for each game without altering the HTML file. The desired outcome should resemble this: I&a ...

Tips for notifying highlighted text in Kendo Editor

How can I provide an alert for a selected text inside the kendo editor? I have attempted the code below <textarea id="editor"></textarea> <script> $("#editor").kendoEditor(); var editor = $("#editor").data("kendoEditor"); var html = edit ...