AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages.

In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this, I am using $routeChangeStart to call an $http service that retrieves all page slugs from the database and allows users to navigate to them.

The issue arises when I add a new page from the backend and attempt to view it. The page slug for the newly inserted record is not retrieved from the database, causing the default route to lead me back to the homepage.

However, upon refreshing the application (pressing F5), the correct route is found.

Below is a snippet of my code:

Route configuration for single page :

$routeProvider.when('/:pageSlug',{ templateUrl:BASE_URL+'singlePage', controller:"pageController"});

$routeChangeStart implementation :

app.run(function($rootScope, $location, loginService, PageUrlService, $route)
{
    var $promise = PageUrlService.getPageUrls();

    $rootScope.$on('$routeChangeStart', function(){

        var pageRoutes = [],
            after = [],
            before = [],
            right = [],
            general = [];


        $promise.then(function(res){
            var data = res.data;

            if(data.status == "found"){
                angular.forEach(data.content, function(value, key){
                    pageRoutes.push("/"+ value.pageUrl);
                });
            }           

            if($rootScope.isLoggedIn == true)
            {
                 // Route access allowed if found in "pageRoutes"
            }
            else
            {
                 // Route access allowed if found in "pageRoutes"
            }
        });
    });
});

Answer №1

app.run function is invoked only once throughout its life cycle.

This ensures that the code snippet below is run just one time:
var $promise = PageUrlService.getPageUrls();

It is recommended to place this code snippet within the routeChangeStart function for optimal efficiency.

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

Can values from a dgrid store be saved in a variable or displayed in the console?

Currently, I am utilizing the dgrid store to display a grid (dgrid 0.4) on my website. Below is the code snippet that I have implemented: require([ 'dojo/_base/declare', 'dojo/Deferred', 'dstore/RequestMemory', ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...

Issues with adjusting the height using CSS transformations are not being resolved

There seems to be an issue with animating the height property of an element as it is not animating at all. Check out the fiddle where the animation is attempted. Here is the HTML: <ul> <li> li 1 </li> <li> ...

What is the best way to define a function in React hooks - using a function statement or

When working with a react hook and needing to define a function inside it, which approach is preferable? useEffect(() => { //... function handler() {} //... }, []); or should I use the newer const declaration instead? useEffect(() => { ...

Universal HTML form validation with a preference for jQuery

Is there a jQuery plugin available for form validation that follows the most common rules? Specifically, I need to validate based on the following criteria: All textboxes must not be empty If the 'Show License' checkbox is checked, then the &a ...

What is the best way to manage a brief webhook timeout in a Node.js environment?

The eSignatures API has been successfully integrated into our app, ensuring smooth functionality up to this point. However, an issue has arisen with the webhook function. When a client signs a document, it triggers our webhook cloud function to update our ...

Using the `on` method of jQuery to make an Ajax request

I'm facing a challenge with using Jquery to load dynamic wall posts for followers. The issue arises when trying to work with dynamic content in the traditional click method. To solve this, I have implemented the on method for the response. However, I ...

The sequence of event handler executions in JavaScript

When multiple event handlers are attached to the same event on the same elements, how does the system determine the order in which they are executed? Although I came across this thread that focuses on click events, another discussion at this page points o ...

Issue with Angular's ng-if directive not properly displaying on the user interface

Recently, I attempted to implement ng-if in my code and it was working fine. However, now when I try to use it again, ng-if seems to not be functioning as expected. Below is an example of how I am using it within ng-repeat. <tr ng-repeat="program in g ...

Running Angular unit tests with Node.js and Karma: A step-by-step guide

I recently dived into creating unit tests in AngularJS, but I'm struggling with setting up Node.js and Karma. To tackle this, I went ahead and downloaded Node.js from nodejs.org and successfully installed it. I then proceeded to the command prompt an ...

Comparison between the sluggishness of radio buttons in Internet Explorer 10 versus Chrome when using jQuery

When using IE 10, Chrome, and jquery 1.10.2 with the standard template from Visual Studio 2013 (.Net 4.5), I encounter an issue with radio buttons. Upon clicking a radio button, two actions are supposed to occur: 1. Recreation of all the radio buttons. 2 ...

What causes the state hook in react to alter every single property within the object?

I have a list of team members and each member is associated with the same set of applications. I created 2 classes to link each member with their respective applications, resulting in a comprehensive list of all members and applications. This list was init ...

Guide on encrypting data on the server with PHP and decrypting it on the client side using JavaScript

I'm currently developing a training website with PHP and I am looking to share my training resources securely without worrying about copyright issues. My plan is to encrypt the documents on the server before sending them, and then have them decrypted ...

What is the method for assigning a value to a variable in xhr.setRequestHeader?

I'm working on setting a value to the variable in xhr.setRequestHeader(Authentication, "Bearer" + parameter); with xmlhttprequest. Can you provide guidance on how to effectively pass a value to the variable within xhr.setRequestHeader? ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

A comprehensive guide on making an AJAX call to a self-hosted servlet

I created a servlet in Eclipse IDE for Java EE that posts data as an XML page and hosted it on a Tomcat server. The servlet can be accessed at http://localhost:8080/Checkers/CheckersServlet. When I open this URL in Firefox, the XML loads correctly. Now, I& ...

Include a class above the specified element; for instance, apply the class "act" to the "<ul>" element preceding the "li.item1"

Hello there! I need some assistance, kinda like the example here Add class and insert before div. However, what I really want to do is add the class "act" to a class above that matches the one below: Here's how it currently looks: <ul> ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

TypeORM reporting duplication error when bulk saving data instead of detecting and ignoring existing records or updating their values

According to the documentation provided by TypeOrm Framework, the Repository.save function is supposed to save/insert new values and ignore/update existing ones. However, I am currently experiencing an issue where it is throwing a duplication error for an ...