How to utilize Angular service during manual bootstrapping / initialization

Is it feasible to access a method from a factory service, prior to Angular being initialized, like demonstrated in the code snippet below?

I have a requirement to make multiple AJAX calls before Angular initialization to set certain global application variables. My initial plan was to handle this logic and store the responses within an Angular service, and then return a promise...

<script src="scripts/app.js"></script>
<script src="scripts/factories/app.js"></script>

<script>
    angular.element(document).ready(function() {

        factoryName.startup().then(function() {
            angular.bootstrap(document, ['MyApp']);
        }, function(err) {
            console.log(error fetching bootstrap data);
        }

    });
</script>

Are there any other approaches available to achieve similar functionality?

Answer №1

To initiate the first service calls, you can utilize module run blocks in AngularJS. Subsequent service calls can then be handled by either serving data from $http's cache or explicitly caching the promise from the initial call.

// Here is an example
myApp.run(function(MyService) {
  // Invoke your function when Angular initializes
  MyService.init();
});

Answer №2

Here is an illustration showcasing the loading of a configuration file prior to bootstrapping the application.

The initial call to bootstrap is made to access angular services such as $http and $location (you also have the option to inject your own module at this stage in order to utilize custom services).

Once the configuration file is loaded, angular.bootstrap is invoked for the main application, with the loaded configuration being defined as a constant on a makeshift module(rsacAppBootstrap) that gets injected.

There are at least two benefits compared to using a promise set from a run block:

  1. Less repetition of promises for all elements relying on configuration
  2. Possibility to selectively load dependencies based on the environment using RequireJS

Customized bootstrap script:

angular.bootstrap().invoke(function ($http, $location) {

  var env = $location.search()._env || null;
  if (env === true) {
    env = null;
  }

  var configUri = 'config/env.json';
  if (env) {
    configUri = configUri.replace('json', env + '.json');
  }

  var rsacAppBootstrap = angular.module('rsacAppBootstrap', [])
    .run(function ($rootScope, $location, $window) {
      var env = $location.search()._env;
      $rootScope.$on('$locationChangeSuccess', function () {
        var newEnv = $location.search()._env;
        if (env !== newEnv) {
          $window.location.reload();
        }
      })
    });

  function bootstrap(config) {
    rsacAppBootstrap.constant('rsacConfig', config || {});
    angular.element(document).ready(function () {
      var modules = ['rsacApp', 'rsacAppBootstrap'];
      if (config.modules){
        config.modules.forEach(function(v){
          modules.push(v);
        })
      }
      angular.bootstrap(document, modules);
    });
  }

  $http.get(configUri)
    .success(function (config) {
      config._env = env;
      if (config.require) {
        require(config.require, function(){
          bootstrap(config);
        });
      } else {
        bootstrap(config);
      }
    })
    .error(function () {
      bootstrap();
    });

});

Sample configuration file:

{
  "_meta": [
    "Development environment settings"
  ],

  "require":[
    "//code.angularjs.org/1.2.3/angular-mocks.js",
    "components/rsacMock/js/rsacMock.js"
  ],

  "modules":[
    "ngMockE2E",
    "rsacMock"
  ],

  "resources": { ... }

}

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

When you click on an element in Angular, it will not fade out as expected, instead displaying the error message "

After pressing the delete button in my twig file, the item is removed but it doesn't fade away as expected. I tried to seek help on this thread but couldn't comprehend the solution. Although the item is being deleted, I am encountering an error ...

What is the best way to insert additional divs into a box div that contains tabs?

My current challenge is as follows: On a webpage, I have a box with jQuery tabs labeled "Enter" and "About" designed to switch the content displayed within the box. UPDATE: The jQuery script in use is shown below: <script type="text/javascript"> ...

Sort data in AngularJS based on mathematical calculations

I currently have a table set up like below: <tr ng-repeat="x in data | orderBy:xxxx"> <td>{{ x.name}}</td> <td>{{ x.price * x.count }}</td> </tr> Is there a way to sort this table based on the {{ x.price * x.co ...

Express.js - Monitoring for server closure

I have a Node.js application that utilizes Express. Within this application, there is a section of code structured as follows: const app = require('./app'); const port = process.env.PORT || 8080; const server = app.listen(port); server.on(&apos ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

How to make an AngularJS list filter case insensitive

I have a collection of subjects that I need to sift through in order to find accurate results. However, the search function is case sensitive and doesn't produce the desired outcome. var subjects = [ {id: '1', name: 'Maths'}, ...

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

Tips for saving data to a file using the frontend

Is it possible for draw.io to write directly to a local file from my browser without the need for any server app or browser extension? I'm not referring to simply downloading a file, but actually writing to a file. For example, when creating a new dia ...

Enhancing Raphael elements with event handling functionality

Greetings! I've been attempting to implement a mousemove and click event on an SVG Raphael Rectangle: Check it out here: http://jsfiddle.net/neuroflux/nXKbW/1/ Here's the code snippet: tile = ctx.rect(x*10,y*(i*10),10,10).attr({ fill:&apos ...

What is the best way to mention @here with an attachment?

I'm attempting to use the canvas say command to display an image with an @here mention included, but unfortunately it only shows the image without making the mention. Below is what I have attempted: message.channel.send(`@here\n`+attachment); ...

Issue with ng-file-upload and Busboy causing upload error on server

I am facing a situation where I need to upload both a .zip file and a .xlsx file to an endpoint simultaneously. On the client side (Angular 1): files.upload = Upload.upload({ url: '/api/files', data: { xlsxFile: xlsxFile, zipFile: zipFile } ...

Expanding Bootstrap 5 navbar-nav to occupy entire screen space in collapsed state

Hello everyone, I hope you are doing well! I am currently working on a website project using Bootstrap 5 and have encountered an issue with the navbar toggler. While the toggler is functioning properly, I am having trouble making it fill the full width o ...

Unable to bring JavaScript into an HTML document

I am diving into the fundamentals of JS and HTML, starting with a simple script. Here is my test.js file: document.getElementById("test").innerHTML = "Loaded js file"; And here is my test.html: <!DOCTYPE HTML> <html lang="de"> <head> & ...

Present a Java-generated JSON object on a JSP page using JavaScript

Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see th ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: https://i.sstatic.net/84cir.png The challenge now is figuring ...

Is there a way to fetch the response of $https in AngularJS before it completes?

When I retrieve 2000 rows from a database, accessing them directly through the API (domain.com/api/contacts/) is fast. However, when I try to display them using ng-repeat with $http, it takes about 10 seconds to load the same data. My question is: Is ther ...

Using JavaScript to Apply CSS Styles in JSF?

Is it possible to dynamically apply a CSS style to a JSF component or div using Javascript? I have been searching without any success. Below is some pseudo code: <div style="myJSStyleFunction("#{myBean.value}")"> stuff </div> The function wo ...

`Is there a recommended approach for conducting a Multi-Factor Authentication test with Cypress?`

I am currently testing an application that sends out a one-time password (OTP) if the user has multi-factor authentication (MFA) enabled. I need to create an end-to-end (E2E) test for this specific functionality. Does anyone know of a tool that can help me ...

Adding multiple variables in jQuery: A guide to mimicking the .= operator from PHP

Being new to jQuery, I'm a bit unsure of how to achieve this. Typically in php, I can accomplish something like this: $result = ''; $result .= 'Hi'; $result .= ' there'; echo $result; I'm simply wondering if there ...