Angular controller handling a resolve operation

I have a scenario where I need to load ngResources in my global/main controller and pause the execution of anything else until they are loaded, similar to how the resolve property works for routes. How can I achieve this?

// Implementing one-time actions in the "global" controller.
app.controller('FrontendCtrl', function($scope, authService, sessionService) {

  // Checking if the user has a cookie and fetching info from the server to reinitiate the session
  authService.updateUser();

  $scope.$session = sessionService;

});

// Authorization service
app.factory('authService', function($q, Auth, Other, sessionService) {

    // Retrieving user data from the server - consists of one main query followed by additional ones using ngResources
    var updateUser = function() {
      Auth.profile(null, function(data) {
        if(data) {
          $q.all({
            foo: Other.foo({ user_id: data.id }),
            bar: Other.bar({ user_id: data.id }),
           })
          .then(function(results) {
            sessionService.user = _.merge(results, data);
          });
        }
      });
    };
});

// Issue in the view - loading delay affecting updateUser function
{{ $session.user.name }}

Answer №1

To ensure the service populates the session value first, callbacks are necessary. Below is the code snippet that demonstrates how to achieve this:

// Implementation of Auth service
app.factory('authService', function($q, Auth, Other) {

    // Retrieve user data from server - initial query followed by subsequent ones - all using ngResources
    return {
      updateUser:  function(callback) {
        Auth.profile(null, function(data) {
          if(data) {
            $q.all({
              foo: Other.foo({ user_id: data.id }),
              bar: Other.bar({ user_id: data.id }),
             })
            .then(function(results) {
              // Only an object instance of sessionService
              callback(sessionService);
            });
          }
        });
      };
    }

});

In the controller:

// The "global" controller where one-time actions are performed on load.
app.controller('FrontendCtrl', function($scope, authService) {

  // Checking for a user cookie and fetching info from server to reinitialize session
  //Update: Callback to retrieve session data
  authService.updateUser(function(data){
    $scope.$session = data;
  });
});

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

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

Transmit information from NodeJS back to the original HTML page following a form submission

On a webpage named "history.html", there is a form with the POST method that gets submitted to a NodeJS server for processing. <form action="/history/find" method="POST"> some form stuff </form> The following code on the server receives the ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

redux reducer failing to update state within store

I am completely new to redux and still have a lot to learn. I am currently working on a project that requires setting up a redux store and using state from that store. However, as I try to update the state through a reducer, the code fails to work properly ...

Is it possible to utilize parameters in a directive in AngularJS?

I am facing an issue where I need to retrieve something in a directive and then set it in the HTML code. How can I accomplish setting something in HTML and getting it in a directive? Here is the HTML code snippet: <div my-directive="Bob"> <d ...

Overriding Protractor's "beforeAll" with an HTTP mock

Using Protractor for End-to-End testing in my application has been a game-changer. In one of my tests, I simulated the backend calls using a MockModule like this: describe('Let's test a new feature', function(){ beforeAll(function () { ...

How can I prevent AngularJS from re-rendering templates and controllers when navigating to a route with the same data?

Is it possible to prevent the templates for the controllers of a route from re-rendering when changing the route, even if the data remains unchanged? ...

jQuery UI - Slider loses its binding after being used once

I'm still learning the ropes, so please bear with me! Currently working on a JavaScript game that is coming along well. I've got the basics of the user interface down, such as menu selections and screen transitions. However, I've hit a road ...

Case-insensitive Matching in JavaScript

Similar Question: Case insensitive regex in JavaScript Potential values to match: - Mike Liam - Joe Mike - Mondal Mike Effron I'm trying to find a match for every value that contains 'Mike' (case-insensitive). This is what I attemp ...

Using React dangerouslySetInnerHTML with iframes

I am facing an issue with a component that displays a WordPress blog post. The post includes HTML markup as well as YouTube embeds using an iframe element. However, dangerouslySetInnerHTML is removing the iframes. How can I ensure this type of content is ...

Cross-origin Resource Sharing (CORS) with Firebase

Initially, I successfully implemented Firebase Functions with the Ionic Native HTTP plugin (https://ionicframework.com/docs/native/http/). However, I recently decided to transition to the Angular-Http method to allow for easier testing in the browser. The ...

Data manipulation with Next.js

_APP.JS function MyApp({ Component, pageProps }) { let primary = 'darkMode_Primary'; let secondary = 'darkMode_Secondary' return ( <Layout primary_super={primary} secondary_super={secondary}> <Component {...page ...

What is causing the added assets to not be saved in the hyperledger registry?

I have the application code below in my Hyperledger composer environment (My question pertains only to the RequestT transaction as I have not yet written the Respond transaction code): Data Model Code (.cto) /* * Defines a data model for chama transactio ...

How can you make a Dropdown Box with Javascript?

My current table setup is as follows: <table> <tbody> <tr> <td>List 1</td> <td>List 2</td> <td>List 3</td> <td>....</td> </tr> <tr> <td>This section would be the dropdown ...

Struggling at the beginning, a basic angular leaflet directive encounters issues

Currently, I'm in the process of incorporating a straightforward leaflet directive into my angular project. The entire code can be found at https://github.com/pluess/woodstore. class MapDirective { constructor() { this.resctrict = ' ...

A guide on dynamically using jQuery to embed an image within a hyperlink tag

I am having trouble with these HTML tags: img = <img data-dz-thumbnail="" target="_blank" alt="twitter-btn-mob.png" src="image.jpg"> a = <a href="javascript:void(0)" target="_blank"></a> My goal is to insert the image tag into the anc ...

What is the best approach: passing state down to child components or allowing child components to access state directly in React?

In my react/redux application, I am faced with the task of having two components - let's call them foo and bar. Foo needs to set a state that bar will use for rendering decisions. Currently, I have implemented a dispatcher in foo to dispatch an action ...

Struggling to form an array of arrays: encountering an issue with data.map not being a function

I have received some data in the following format: const mockData = [ { "1": [ { val1: 0.9323809524, val2: 5789.12, val3: 84.467, val4: 189.12, val5: 8, bins: 1, }, { ...

Learn how to efficiently print data from an object in AngularJS without repetition

My objective is to display an object using ng-repeat while taking into account that some keys are duplicated. I would like the duplicate keys to be displayed only once, and for the average of their similar values to be calculated. Here is the data: [ ...

Bottom dynamic div

I have three divs: head, foot and textbox. The head and foot divs are fixed positions, and the third div is partly fixed (margin-top). My query is: How can I adjust the bottom of the textbox's div to accommodate different monitor sizes? Using 100% h ...