Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet:

.run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $location, UserService, CompanyService) {
  $rootScope.globals = {};

  $rootScope.$on('login', function(event, data) {
    $rootScope.api_key = data.api_key;
    CompanyService.get(data.user.company_id);
  });

  UserService.checkAuth().then(function(response) {
    if(response.data.user) {
      // User is logged in
      $rootScope.$broadcast('login', response.data);
    } else {
      UserService.logout();
    }
  });
}]);

This section primarily focuses on checking whether a user is currently logged in. If they are, we proceed to identify their corresponding company using the CompanyService:

angular.module('mean').service('CompanyService', ['$http', '$rootScope', function($http, $rootScope) {
  var company = this;
  company.company_data = {}

  company.getCompany = function() {
    return company.company_data;
  }

  company.get = function (company_id) {
    return $http({
      url: '/api/v1/company/' + company_id,
      method: 'GET',
      headers: {
        api_key: $rootScope.api_key
      }
    }).success(function(response) {
      if(response.status === 'ok') {
        company.company_data = response.company;
      }
    });
  };
}]);

Further along in the code, there's an instance where a particular function relies on the singleton CompanyService for making an API call:

  $scope.index = function() {
    LocationService.get(CompanyService.getCompany()._id, $routeParams.location_parent_id).then(function(response) {
      if(response.data.status === 'ok') {
        $scope.locations = $scope.locations.concat(response.data.locations);
      }
    });
  }

A challenge arises when, upon refreshing the page, this specific call sometimes occurs prior to populating data into the CompanyService singleton. How can promises be effectively utilized to ensure that the LocationService operation is delayed until after the necessary data is available within the CompanyService singleton?

Answer №1

If you want to maintain your current code structure while ensuring the CompanyService data is available before proceeding, one approach is to create a promise that resolves once the data is ready. It's important to note that error handling still needs to be implemented...

angular.module('mean').service('CompanyService', 
        ['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
    var company = this;
    company.company_data = {}

    var initializedDeferred = $q.defer;
    company.initialized = initializedDeferred.promise;

    company.getCompany = function () {
        return company.company_data;
    }

    company.get = function (company_id) {
        return $http({
            url: '/api/v1/company/' + company_id,
            method: 'GET',
            headers: {
                api_key: $rootScope.api_key
            }
        }).success(function (response) {
            if (response.status === 'ok') {
                company.company_data = response.company;
                initializedDeferred.resolve(); // handle errors here?
            }
        });
    };
}]);

$scope.index = function () {
    CompanyService.initialized.then(function () {
        LocationService.get(CompanyService.getCompany()._id,
            $routeParams.location_parent_id).then(function (response) {
            if (response.data.status === 'ok') {
                $scope.locations = $scope.locations
                      .concat(response.data.locations);
            }
        });
    });
}

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

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

Unable to obtain a response even after providing the correct API key in a Node.js POST request

Can you please assist me in troubleshooting the POST request code below? Here is a snippet of the code: const express = require("express"); const bodyParser = require("body-parser"); //const request = require("request"); const https = require("https"); c ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

What criteria does Angular use to determine when the aot compiler should be utilized?

This page discusses the concept of modules in Angular and explains the two approaches to bootstrapping - dynamic and static. The configuration for these approaches is typically found in main.ts: // Using the browser platform with a compiler import { platf ...

How can I create a static navigation bar and sidebar using Bootstrap 4?

Currently, I am utilizing HTML, Javascript, Bootstrap, and CSS to develop a fixed navbar and sidebar for our system. My objective is to ensure that the navbar and sidebar remain fixed even when users scroll down the page, while also maintaining responsiven ...

I understand the reason behind the unexpected { token error, but I'm unsure of how to resolve it when my PHP script needs to transmit a collection of data to JavaScript

I am currently utilizing this JavaScript fetch code to retrieve data from PHP async sendRequest(selectValue=this.selectValue){ const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue); const fetchJSON = await fe ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

Top Pagination Tool for Angular Web Development

Currently, I am developing an Angular and Bootstrap application and in need of a reliable pagination plugin. Can you recommend the best one for me to use? I have experimented with a plugin available at: https://github.com/michaelbromley/angularUtils/tree/ ...

What is the method to obtain the keycode for a key combination in JavaScript?

$(document).on('keydown', function(event) { performAction(event); event.preventDefault(); }); By using the code above, I am successful in capturing the keycode for a single key press. However, when attempting to use a combin ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Experiencing difficulties while attempting to organize an array?

// const first = data.groups_with_selected[7]; // const second = data.groups_with_selected[20]; // data.groups_with_selected.splice(2, 0, first, second); // data.groups_with_selected.splice(9, 1) // data.groups_with_selected ...

Ways to reveal concealed div elements when hovering the mouse?

Is there a way to display a group of hidden div's when hovering over them? For instance: <div id="div1">Div 1 Content</div> <div id="div2">Div 2 Content</div> <div id="div3">Div 3 Content</div> All div's sho ...

Can someone explain why Array.from(classList)[0] is not changing to 'className'?

HTML Design <div class="custom-container color-red"> <h3>Hello, I am a customized container</h3> </div> Javascript Logic let element = document.getElementsByClassName('custom-container')[0]; let clas ...

When attempting to print the content inside a Bootstrap modal, the display does not appear but instead a blank page is printed

My goal is to print the text content of a bootstrap modal while leaving space for images blank when clicking the print button located within the modal. Unfortunately, upon clicking the print button, I am only getting a blank page without any content displ ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

Issues with AngularJS radio button functionality

Hey there, I am currently using AngularJS in my project. However, when I attempted to add a span to one of my input fields, all the radio buttons related to it stopped functioning. Can anyone offer some suggestions on what might be going wrong here? < ...

Creating a dropdown menu in Bootstrap 4 using JSON information

I am trying to create a dynamic drop-down menu using an input field with a drop-down button inside a form. Currently, I am attempting to populate the drop-down menu with static JSON data. However, I am encountering issues with getting it to function proper ...

Retrieving ID of an element to be animated with jQuery

I have a sprite image that changes background position when hovered over, and while it's currently working, I'm looking for a more efficient way to achieve this. I need to apply this effect to several images and am exploring ways to avoid duplica ...

Guide to retrieving RabbitMQ queue messages in Vue.js application

I am currently working on a project using Spring Boot to publish messages to RabbitMQ and then push them to a queue. I also have a Vue.js frontend application that needs to consume these messages from the RabbitMQ queue. Despite searching online, I haven ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...