Angular Resolve Upon Application Reloading

Is there a way to postpone the initialization of my Application Controller (similar to using the 'resolve' attribute in the router) when reloading a page? Or more importantly, how can I delay the rendering of the view until my controller has successfully retrieved the user object upon page reload?

Currently, I have this code snippet at the beginning of my ApplicationCtrl:

if (localStorage.getItem('token') && localStorage.getItem('token') != 'null')
{
    sessionStorage.setItem('token', localStorage.getItem('token'))
}
if (sessionStorage.getItem('token') && sessionStorage.getItem('token') != 'null')
{
    UserSvc.getUser()
    .then(function (response) 
    {
        loadUser(response.data)
    })
    .then(function (error)
    {
        if (error) $scope.logout()
    })
}

This piece of code verifies the authentication token and then fetches the user object from the database based on that token.

The issue here is that the user data appears with a slight delay after the page loads. This results in an empty navigation bar initially, which is then populated with the user's display name a few milliseconds later.

Is there a way to defer displaying the view until the initial user request has been successfully completed?

Answer №1

After some troubleshooting, I found a solution. I added a new $scope boolean called $scope.initResolved at the top level. This boolean is set to true once the initial user check is completed, regardless of whether a user is retrieved or not. The header and ng-view are then conditionally rendered based on ng-if="initResolved".

$scope.initResolved = false

    if (localStorage.getItem('token') && localStorage.getItem('token') != 'null')
    {
        sessionStorage.setItem('token', localStorage.getItem('token'))
    }
    if (sessionStorage.getItem('token') && sessionStorage.getItem('token') != 'null')
    {
        UserSvc.getUser()
        .then(function (response) 
        {
            loadUser(response.data)
            $scope.initResolved = true
        })
        .then(function (error)
        {
            if (error) $scope.logout()
            $scope.initResolved = true
        })
    }
    else if ($location.url() == "")
    {
        $location.path('/welcome')
        $scope.initResolved = true
    }
    else $scope.initResolved = true

Answer №2

To implement this, you need to place the following code in the resolve section of your state. The customService will provide a UserStatus object that contains a promise. You can then inject this service into your controller, and the controller will wait for the dependency to be resolved.

resolve: {
    'UserStatus': function(UserSvc) {
        if (localStorage.getItem('token') && localStorage.getItem('token') !== 'null') {
            sessionStorage.setItem('token', localStorage.getItem('token'));
        }
        if (sessionStorage.getItem('token') && sessionStorage.getItem('token') !== 'null') {
            return UserSvc.getUser();
        }
    }
}

Controller

app.controller('myCtrl', function(UserStatus, $scope){
   UserStatus.then(function(data){
      //you will receive the response here
   })
})

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

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

What is the best way to transform HeadersInit into an Object<string,string> data type?

In short, I am faced with the task of converting the headers of a RequestInit into a format that another library can comprehend. This particular library requires the headers to be in the format of Object<string, string>. Initially, I attempted someth ...

Setting up Webpack for Node applications

My current challenge involves configuring Webpack for a node app that already exists. I am encountering various issues and struggling to find solutions or even know where to begin. Situation The project's folder structure is as follows: +---app +-- ...

Display loader until the document body has finished loading

Many developers have shared solutions for displaying a loader while an element is being loaded. However, my challenge is unique. I want to display a loader before the document body is fully loaded. The issue arises from an AJAX call in my code: var url = ...

Enhancing next-auth and i18n functionality with middleware in the latest version of next.js (13) using the app

Currently, I have successfully set up next-auth in my next.js 13 project with app router, and it is functioning as expected. My next step is to incorporate internationalization into my app following the guidelines provided in the next.js documentation. How ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

Issue: Spaces are not being displayed between items in the @Html.DisplayFor statement within the Foreach

I have encountered a few similar queries on this platform and attempted the suggested solutions, but unfortunately, they did not resolve my specific issue. Within my view, I am using @Html.DisplayFor in a Foreach loop to display all GroupIDs in a particul ...

Is Node.js functioning properly, but how can I incorporate it into a web browser?

I have a SQL Server table that I want to display in a web browser using the DataTables jQuery plugin. The code below works well for outputting data in the command line, but I need it to be displayed in the browser, possibly in JSON format. I am utilizing ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

When working with a barcode font in Chrome, using style.fontFamily may not be effective, but utilizing className can achieve the desired result

Take a look at this HTML snippet: <style> .barcode { font-family: 'BC C39 3 to 1 Medium'; } </style> <div><span id='spn'>1234567</span></div> This code will apply a barcode font style: <script> ...

Using JavaScript to interact with text elements in external SVG documents

When it comes to creating an SVG within HTML and assigning specific IDs to text elements for easy access, everything works smoothly. For example, I can easily retrieve the ID using: let callQSO = document.getElementById("QSOcall").value; and th ...

Unable to comprehend the process of obtaining a specific value from an array through a recursive function call

My apologies for the confusing question, but let's delve into it: function sum(arr, n) { // Only change code below this line if (n <= 0) { return 0; } else { return sum(arr, n - 1) + arr[n - 1]; } // Only change code above this line } var ...

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

Exploring the Contrast between window.location.href and top.location.href

I'm curious about the distinction between window.location.href and top.location.href. Can anyone explain this to me? Furthermore, I'd like to know when it's appropriate to use each one. Which option is more suitable for redirection after a ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

"Enhance your data management with Laravel and Vue.js by incorporating the powerful Matfish Vue-Table

Currently, I am utilizing matfish-vue-table2 along with server-side implementation. Below is my Laravel controller where I am able to retrieve the JSON response from the 'api/articles' URL: public function index() { $articles = Article::orde ...