Wait for the asynchronous method to finish before displaying the page

My question is similar to this one:stop angular-ui-router navigation until promise is resolved

Despite exploring various answers, none have successfully addressed my issue.

In my application, a cookie containing a token is stored. Upon page load (such as after pressing F5), the application checks for this cookie. If it exists, the token is used to retrieve user settings from a web service. These settings are crucial for accessing information from other web services that my controllers will call, hence they need to be loaded before rendering the page.

Below is the snippet of my current code:

    $rootScope.$on( '$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
        e.preventDefault();

        authentication.checkCookie(function() {
            if (toState.name == 'login'){
                if(authentication.getLoginData()) {
                    //e.preventDefault();
                    $state.go('pricelist');
                }
            } else {
                if(!authentication.getLoginData()) {
                    //e.preventDefault();
                    $state.go('login');
                }
            }

            // No redirect is needed - now render the page requested
            $urlRouter.sync();
        });

    });

Regrettably, this code has not been successful as it leads to an infinite loop.

How can I ensure that the rendering process only proceeds once the cookie is checked and the user settings are fully loaded (which is also done in checkCookie)?

Answer №1

After some trial and error, I was able to resolve the issue by incorporating a different method from the provided source:

    $rootScope.$on( '$locationChangeStart', function(event, next, current) {
        if ($rootScope.locationChangeBypass) {
            $rootScope.locationChangeBypass = false;
            return;
        }

        event.preventDefault();

        authentication.verifyToken(function() {
            $rootScope.locationChangeBypass = true;
            if (next == 'login'){
                if(authentication.isUserLoggedIn()) {
                    $location.path('/dashboard');
                } else {
                    $location.path(next);
                }
            } else {
                if(!authentication.isUserLoggedIn()) {
                    $location.path('/login');
                } else {
                    $location.path(next);
                }
            }
        });

    });

While it may not be the most elegant fix, it does get the job done.

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 the best way to replace a regular expression in JavaScript?

I've recently been exploring the functionalities of MathJax, a Javascript library that enables the use of LaTex and similar mathematical markup languages within HTML. However, when attempting to incorporate it into my Javascript code, I encountered so ...

Issue with Javascript functionality not persisting after page reload initiated with a href = '#'

I am facing an issue with a button on my webpage that is meant to redirect and reload the home page. However, after redirection to '#', my JavaScript seems to stop functioning correctly. Currently, my JavaScript code is enclosed within window.on ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

Step by step guide on retrieving the selected items from a kendo treeview

HTML CODE: <div> <md-button ng-click="getCheckedItems()">TEST</md-button> </div> <div kendo-tree-view="tree" ...

Combining two objects using three.js is not possible due to concatenation

I am attempting to combine two objects (bar and circle) to create a ping pong racket in three js, Even after using var parent = new THREE.Object3D();, the objects remain separate This is the code for my function : function addPaddle() { var paddl ...

Tips for maintaining table elements in place using JavaScript

My goal is to keep the tags within the table fixed when printing. The code I've written functions correctly in View mode, however, when printed using JavaScript, if one of the columns is too large, the rest of the columns get displaced. I want all col ...

Build a Search Suggestions feature with Node Package Manager (NPM) and Model-View-Controller (M

Stepping into the exciting world of MVC core and harnessing NPM for JavaScript packages has been a learning curve. However, I've encountered an issue that requires some deliberation on the best course of action for resolution. To provide context, I ha ...

Accessing one controller from another module in AngularJS using TypeScript is a common challenge that many developers face. In this article, we

// inside engagement.component.ts: class EngagementMembersController { alphabetic: Array<string> = 'abcdefghijklmnopqrstuvwxyz'.split(''); constructor() {} export const EngagementSetupMember: IComponentOptions ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

What is the process for incorporating a file using ng-include?

I'm trying to incorporate an svg file into my template. data.data.svg = 'test.svg' console.log(data.data) {'svg' : 'test.svg'} Although data.data contains other data, the above object represents how the svg element appe ...

The functionality of window.event.target appears to be malfunctioning in the Firefox browser

I have been working on an angularjs application. We have implemented a functionality to display alerts for unsaved changes using window.event.target. Everything was functioning correctly in all browsers except for <code>Firefox. The error message w ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

When trying to upload a file to S3 using a presigned URL, a 403 error

Using Node.js to generate a presigned URL for Amazon S3 in order to upload an image to a bucket. var aws = require('aws-sdk'); // Retrieve presigned URL from S3 exports.S3presignedURL = function (req, res) { var s3 = new aws.S3(); var params ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

continuously repeating with each press of the enter key

Whenever I focus on the input field and press enter, everything works fine. However, if I do it again, the action is repeated multiple times depending on how many times I focus. $(document).delegate(".changeValue","focus one",function(){ $(this ...

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

Develop a routing system for a complex Angular application with multiple modules

As a newcomer to Angular, I am exploring a multi-module structure within my Angular app. Each module such as login, user, and report contains one or two components. My current focus is on implementing routing, with the requirement that the login page must ...

Displaying an undefined value using ExpressJs (to present an [object])

While learning expressjs, I encountered an issue where the value I passed did not appear in the output. I created a new Routes file and defined a function with Route methods in it. However, when I set Route paths, the value did not show up in the output. A ...

"Troubleshooting: Unable to Get ng-repeat to Work in AngularJS

Having trouble using ng-repeat in AngularJS 2 with a custom template html <tr ng-repeat="data in itemList"> <td>{{data.test}}</td> </tr> .ts import {Component, View} from "angular2/core"; @Component({ selector: 'my- ...