Global variables in AngularJS that are asynchronous

My challenge lies in using AngularJS to create several global objects accessible by any controller within the application.

One crucial object I require is a user object containing the user's ID and other essential properties retrieved from the database via Ajax. The goal is to establish this user object, then initialize the controllers utilized on the page for an effective initial load of the program.

If the user object remains unset, a redirection becomes necessary.

I am seeking a clean solution for this issue. Despite my attempts with broadcasting, the code is becoming convoluted.

At present, I utilize ui-router and have a hidden view employing a GlobalsCtrl controller. This controller uses a service to fetch the objects and subsequently $broadcasts them for controller initialization. However, this broadcasting solely functions during the initial site load. Events are not broadcasted when changing $location.paths due to the pre-set variables in GlobalsCtrl.

Implementing conditional statements seems like a messy workaround to me.

Your insights would be greatly appreciated. Thank you!


Plunker - http://plnkr.co/edit/TIzdXOXPDV3d7pt5ah8i

var app = angular.module('editor.services', []);
app.factory('AnalysisDataService', ['$http', function($http) {
    var self = this;

    self.activeAnalysis = {};

    self.openAnalysis = function(analysisId) {
        return $http.get('api/v1/assignments/analysis/' + analysisId)
            .success(function(data, status, headers, config) {
                self.activeAnalysis = data;
                return self.activeAnalysis;
            }).error(function(data, status, headers, config) {
                console.log("Error could not load analysis article.");
            }).then(function(result) {
                return self.activeAnalysis;
            });
    };

    self.getAnalysis = function() {
        return self.activeAnalysis;
    };

    self.navigateToStep = function(step) {
        $location.path('/analysis/summary');
    };        

    return {
        open: self.openAnalysis,
        get: self.getAnalysis,
        navigate: self.navigateToStep,
    }
}]);

The issue arises as I necessitate setting the self.activeAnalysis variable before certain controllers load. Each page displays differing datasets based on the analysisId.

Answer №1

In AngularJS, ui-router provides a resolve method within routes for handling asynchronous data loading.
Using resolve, you can instruct the routing to wait and resolve certain tasks before transitioning to a new route.

For instance, if you encounter issues similar to authentication, consider exploring these resources:

Answer №2

If you want to ensure that promises are resolved before transitioning to a new state using ui.router, one approach is to implement a resolve in the route configuration. Here's an example:

.state('app.feature', {url: '/my-feature/',
    views:{
      'mainView': {
        templateUrl: '/views/mainView.html',
        controller: 'mainController'
      }
    },
    resolve: { 
      featureData: function (featureService) {
        return featureService.fetchFeatureInfo();
      }
    }
  })

In this setup, the promise returned by

featureService.fetchFeatureInfo()
will be resolved prior to moving to the new state. Ensure that the response data is stored within the service for access in the controller.

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

Exploring the geographical boundaries of a Google Map region using coordinates and polygons

In my quest to develop an Angular application heavily reliant on Google Maps, I aim to showcase areas on the map based on continent -> country -> state -> suburb. The color of these highlighted areas will be determined by the values supplied. I h ...

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

Create a search preview in JavaScript that emphasizes key information and provides a condensed overview

I am currently working on incorporating a feature that generates a highlighted and condensed preview of a provided text. Below is the code snippet I have so far: <div> Search: <input value='vestibulum' disabled/> </div> < ...

How can an Express.js server detect when a browser has been closed or reloaded?

Currently tackling a project with an Express.js server. One query I have is how can this server detect when one of its users (browser) has been closed or reloaded? Any insights on this would be greatly appreciated! ...

What are the steps to retrieve JSON data and display it using an unordered list in an HTML document?

My JSON data structure looks like this: { "fID": "00202020243123", "name": "John Doe", "List": ["Father", "Brother", "Cousin"] } When I render this JSON element in my model and view it in the HTML, everything works fine. However, when I try t ...

Refreshing a view in Laravel after a successful insertion using JQuery Ajax

I have been successfully inserting records into a table using jQuery ajax, and receiving a flash message confirming the successful insertion. However, I am now facing an issue where I do not know how to reload the table to reflect the changes after the rec ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

I am facing an issue with the responsiveness of the mat-card component within a div in

Is it possible to display several small paper cards in a div so that they wrap around the container? ...

Conceal the Ajax Div and display the Loader Div while waiting for the data to be

Trying to show a loader div until the Ajax-populated div is returned. Want to hide "responseDiv" until it's filled with Ajax data and display a loading div in the meantime. #loading { background: url('images/loading.gif') no-repeat cent ...

Tips for swapping out the content within a "li" element

I am dealing with a situation where I have approximately 100 pages, all containing an <ul> tag, but the issue is that I need to enclose each list item within a <span> tag. Below is the code snippet I have tried: <ul style="list-style-type: ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

The error message thrown is: "Unable to assign headers after they have already been sent to the client."

I've been attempting to make a GET request, but it keeps failing at the app.js res.json line. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

What are the steps involved in converting a MERN application into a desktop application?

As a beginner in front-end application development, I recently created a MERN application in React with separate frontend and backend parts. Everything is working smoothly, but now I want to convert it into a desktop application that can run independently ...

Javascript eval function providing inaccurate results

I have encountered a problem while using eval() for a calculator I am developing. When I input the following code: console.log(eval("5.2-5")); The output is: 0.20000000000000018 I am confused as to why this is happening. Thank you for your assistance. ...

Developing with Asp.Net has never been easier thanks to the UpdatePanel feature which

Every time I press the "Test" button, only one textbox is generated. If I click twice, I expect two textboxes to appear. I attempted this solution, and it seems to work well except for one issue. The textbox is recreated each time so the user's input ...