What is the best way to load data that is essential for the entire functionality of an AngularJs Application?

Within my application, there exists essential data that is utilized by various controllers to carry out their functions.

For instance, the user and other entities must make REST calls to the server. Currently, I have an AppController (app.js) responsible for loading fundamental data needed by all controllers within ng-views (refer to index.html). The methods loadUser() and loadRequiredEntity() store values obtained from REST calls in indexedDb.

Each controller within ng-views displayed on the index.html reads the loaded data from indexedDb. However, there seem to be some significant issues with this approach:

  • Does the AppController ensure that all data is loaded before ng-view controllers attempt to access it?
  • The loadUser() and loadRequiredEntity() functions initiate services (e.g., userService) that execute rest-calls and return promises, causing AppController to finish before all data is fully loaded. Consequently, ng-view controllers could start reading from indexedDb before any values are stored there.

How can I effectively load the necessary basic data for other controllers' use? Is an AngularJS controller the most suitable option?

index.html:

<body ng-app="app" id="appBody" ng-controller="AppController as appCtrl">
    <md-content id="content" ng-view=""></md-content>
</body>

app.ts:

/// <reference path="../typings/tsd.d.ts" />
module app {
      export class AppController {

          static $inject = ['$log'];

          private _LOG_PREFIX : string = 'AppController: ';

          constructor(private $log: ng.ILogService) {
          this.$log.info(this._LOG_PREFIX + 'started');
          this.loadUser()
          .then(this.loadRequiredEntity)
          .then(this.markAsAuthenticated, this.handleLoadBasedataError);
          }
          ...
      }
}

Answer №1

Storing and Accessing Data: It is recommended to store your data in a service, such as UserService. Making $http calls should be done from services only. This practice is based on opinions shared by many developers, as seen in resources like this popular style guide

Loading Data Before Controllers: In your router configuration, you can set up a resolve option (available in both angular default router and ui-router). Utilize this resolve option to fetch data before navigating to different pages within your app. Check out examples in ui router or in default router

  1. Within the resolve function, make a call to userService.load()
  2. In each controller, access the loaded data using methods like: userService.getUsers()

Answer №2

As mentioned by Melou, the issue is resolved by using ui-router.

The initial data is retrieved and loaded in an abstract state.

module app.core {
    "use strict";
    import LoadBasicDataService = app.core.services.LoadBasicDataService;

    function retrieveBasicDataForControllers(loadBasicDataService: LoadBasicDataService) : ng.IPromise<any> {
        return loadBasicDataService.load();
    }
    retrieveBasicDataForControllers.$inject = ['loadBasicDataService'];

    function configureCore($urlRouterProvider: angular.ui.IUrlRouterProvider, $stateProvider: angular.ui.IStateProvider){

    $urlRouterProvider.otherwise("/myComponent1");        

    $stateProvider
        .state("main",{
           templateUrl: "layout/main.html",
           abstract: true,
           resolve: {
               'retrieveBasicDataForController': retrieveBasicDataForControllers
           }
        })
        .state("main.myComponent2",{
           url: "/myComponent2",
           template: "<myComponent2></myComponent2>"
        })
        .state("main.myComponent1",{
           url: "/myComponent1",
          template: "<myComponent1></myComponent1>"
       });
    }
   configureCore.$inject = ["$urlRouterProvider", "$stateProvider"];

angular
.module("app.core")
.config(configureCore);
}

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

How can you effectively retrieve values in Chakra Core without encountering any memory complications?

I have been studying this example in an effort to develop a basic JavaScript engine that can execute scripts like the zxcvbn library. I thought I had it all figured out, but there are certain parts of the code that still puzzle me. Particularly, I am strug ...

Days and Their Corresponding Names Listed in Table

Currently, I am working on creating a "timesheet" feature that requires the user to input 2 dates. The goal is to calculate each month and year based on the input dates and then display them in a dropdown menu combobox. I would like to dynamically update ...

Mapping an object in a table only results in the final value being displayed

I am facing an issue with my data object containing an array of data that I have mapped inside a table. The problem arises when I try to retrieve the id value of any item in the table's rows using console.log(). It always returns the id of the last it ...

Receive the Navigating event upon a new browser window opening with the help of the WebBrowser control in JavaScript

In my C# / .NET 4 project, I have a form containing a WebBrowser component that loads an external web page. An event handler is connected to the Navigating event which usually works well. However, there is an issue when a specific part of the loaded websi ...

Differences between using Array.from and a for loop to iterate through an array-like object

When traversing an array-like object, which method is more efficient for performance: using Array.from( ).forEach() or a traditional for loop? An example of an array-like object would be: let elements = document.querySelector('#someid').children ...

The function highcharts() is not defined for $("#highcharts-2i5ujpv-2")

I'm working on an AngularJS application and using highcharts-ng version 0.0.86 to generate a highchart with the following code: <highchart config="highchartsNg"></highchart> The chart is being generated successfully with the dyn ...

Use Object.assign to swap out the current state with a new

Why does the React component with state { key: bool } not omit the existing state key from the new state when a different option is clicked? Link to the code var SampleComponent = React.createClass({ getInitialState: function() { return {}; }, ...

Ways to utilize two distinct XPATH values for a single key

When dealing with Xpath for the same object in two different portals, the paths can be: //*[@id="abc"]/fieldset/div/div/div[1]/label //*[@id="xyz"]/fieldset/div[1]/fieldset/div/div/div[1]/label In order to use both values in the same key and have Seleni ...

Dynamically insert letters into each row as the HTML table increases

How can I display dynamically increasing alphabets in a newly generated cell on the left side of each row, based on the option selected in a dropdown list? These alphabets will serve as bullet points or serial numbers for the text boxes in each row. View ...

Javascript object attributes

Could you retrieve the value of one object property based on the value of another property? For instance, in an SQL query, is it possible to fetch the id from the object where the object.name equals "somename"? I am trying to obtain the id of a particula ...

The server is constantly sending data through Server Sent Events

I am currently a student working on a project involving a social trading platform. I am looking to incorporate a notification system and believe that SSE would be a great fit for this purpose. However, I am facing an issue where my SSE code is sending data ...

I intend to extract the long_name value from the JSON data using AngularJS

I have been attempting to retrieve the long_name from the JSON data below using angular js, but unfortunately I am unable to successfully fetch it. CODE: { "results" : [ { "address_components" : [ { "long_name ...

Maximizing jQuery DataTables performance with single column filtering options and a vast amount of data rows

My current project involves a table with unique column select drop-downs provided by an amazing jQuery plug-in. The performance is excellent with about 1000 rows. However, the client just informed me that the data could increase to 40000 rows within a mont ...

Is it possible to utilize an alias in conjunction with the NodeJS require function?

I have a JavaScript module written in ES6 that exports two constants: export const apple = "apple"; export const banana = "banana"; In another module, I can import these constants as follows: import { apple as a, banana as b } from 'fruits'; c ...

Exploring the Synergy Between Play 2.3.x, Webjars, and Requirejs: Unveiling

Queries: Is there a way to streamline the process of setting paths and shims in requirejs for webjars and their dependencies without manual intervention? (Especially for webjars that include a requirejs.config() call?) Does anyone have a straightforward e ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Constructing hierarchical objects in JavaScript

I am looking to create a complex nested object in JavaScript that follows a specific structure. const data = { name: 'Context 1', children: [ { name: 'Option 1', children: [ { name: 'Context&ap ...

Downloading EJS File instead of Displaying on Express.js Router

As I embark on the journey of developing a live video sharing/watching feature using Pure Node.js and without relying on any frameworks, an unexpected issue arose in the middle of the process. The problem occurred when Express started downloading an EJS fi ...

Having trouble with your HTML5 canvas?

Below is the JS code snippet: function DisplayText(output, x, y){ var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillText ("A" , x, y); ctx.font = 'bold 20px sans-serif'; ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...