Place the `service` parameter into the `run` function

What are some examples of when to utilize the angular.run method? I have a service that is resource-intensive and takes a significant amount of time to initialize before it can be used in conjunction with my view.

angular.module('myApp').service('heavyService',function($timeout){ 
       this.someAjaxCall=function(){

       } 
});

angular.module('myApp').run(function(heavyService){
      // How can I incorporate my heavyService here and then later use it throughout the application
});

How can you inject a service within the run method and subsequently utilize it within the application?

Answer №1

Sequence of Execution:

  1. app.config()
  2. app.run()
  3. compile functions of directives (if present in the DOM)
  4. app.controller()
  5. link functions of directives (if found again)

Run blocks - These blocks are executed after the injector is created and are utilized to initialize the application. Only instances and constants can be injected into run blocks, preventing further system configuration during runtime.

source

angular.module('myApp').run(['heavyService', function(heavyService) {

}]);

Answer №2

Have you considered implementing something like the example below? (Referencing John Papa's style guide "Route Resolve Promises"):

// route-config.js
angular
    .module('app')
    .config(config);

function config($routeProvider) {
    $routeProvider
        .when('/avengers', {
            templateUrl: 'avengers.html',
            controller: 'Avengers',
            controllerAs: 'vm',
            resolve: {
                moviesPrepService: moviesPrepService
            }
        });
}

function moviesPrepService(movieService) {
    return movieService.getMovies();
}

// avengers.js
angular
    .module('app')
    .controller('Avengers', Avengers);

Avengers.$inject = ['moviesPrepService'];
function Avengers(moviesPrepService) {
      var vm = this;
      vm.movies = moviesPrepService.movies;
}

In essence, this approach prepares the service and fetches all the necessary data via AJAX before resolving the route. Once that process is completed, access to the static data in the controller is then available.

Answer №3

The run block in AngularJS is essential for initializing values that need to be accessible throughout the application. By injecting services into the run block, you can initialize service variables that will remain consistent across all components as services are singleton objects.

Sample Code:

// Initialization block
angular.module('myApp').run(function(heavyService){
     // Access service variables and methods here
     // Set value of a variable before it is requested by any controller
     heavyService.someVariable = 'Initial Value'; 
});

In the config phase, you can also set initial values for variables or perform configuration settings. However, the config block does not have access to services directly; they only interact with providers and do not have access to $rootScope during this phase.

The benefit of setting values within the run block is that it has access to $rootScope and can handle route-related events like $locationchangestart, $locationchangesuccess, $routechangestart, etc.

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

What is the impact of memory on NodeJS performance?

Currently delving into a book on NodeJS, I stumbled upon an intriguing example: const express = require('express') const bodyParser = require('body-parser') const app = express() var tweets = [] app.listen('8000', '172 ...

Error: 'require' is not recognized as a valid command - Node.js

I recently attempted to integrate the d3-gauge plugin into a basic node.js/express server. Following the default directory structure generated by Express, I organized the files from the 'example' folder as follows: . ├── app.js ├── b ...

Encountering an issue with my Discord bot where it displays the error message "Unable to access property 'cache' of an undefined object"

I encountered an issue while setting up discord-xp for my bot. Whenever I attempted to use the leaderboard command, an error message popped up: username: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).username : "Unknown" ...

Is it possible to receive returned string values using fetch()?

I have implemented a fetch method in my separate register.js file to handle registration on the front end. However, I am encountering an error when trying to POST the data and receive the following message in the browser console: "Uncaught (in promise) Syn ...

Transmitting information from Angular to Laravel

Hey, I'm facing a challenge once again. Currently, I am working on creating a to-do list application using Laravel and Angular. While I can successfully retrieve data from the database through the Laravel and Angular controllers, I'm encountering ...

Having trouble displaying options in VueJS Component using datalist

Currently, I am harnessing the power of VueJS and its components to create an extensive array of datalists and selectors, each equipped with a submit button for validation upon form submission. Initially, I successfully implemented a datalist within a com ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

Error Encountered in AngularJS: Request Unexpected (No Additional Requests Anticipated)

In my AngularJS project, I'm facing a challenge in writing unit tests to verify that executing a promise's then function changes the location.url. The function login within the AuthenticationService service is responsible for this behavior. Belo ...

Exploring the depths of mongodb through targeted field queries

I am working with a collection of objects structured like this : var Meetup = new Schema({ name: String, text:String, }); My goal is to retrieve all meetups whose name contains a specific string. Below is the API code snippet : module.exports. ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Utilizing Vue JS to set an active state in conjunction with a for loop

Currently in Vue, I have a collection of strings that I am displaying using the v-for directive within a "list-group" component from Bootstrap. My goal is to apply an "active" state when an item is clicked, but I am struggling to identify a specific item w ...

Is the information not displayed in its entirety on the FullCalendar?

I'm currently working with the following code: $('#calendar_1').fullCalendar({ header : { left : 'prev,next today', center : 'title', right : 'month,agendaWeek,agendaDay' ...

What is the best method to initialize a JavaScript function only once on a website that uses AJAX

Currently, I am facing an issue with a javascript function that needs to be contained within the content element rather than in the header. This is due to a dynamic ajax reload process which only refreshes the main content area and not the header section. ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...

`enable cookie sharing between subdomains with the combination of express and angularjs`

I've been struggling with a task for quite some time now without any success. I would greatly appreciate it if someone could assist me with this. Present Scenario: I have two applications running on two sub-domains: st.localhost:8080 and acm.loca ...

Submitting values in URI through an HTML form

Hey there, I'm really in need of some assistance with this issue that's been driving me crazy... :) So, I'm working on a project using Symfony2 and AngularJS: <form class="navbar-form navbar-right" role="form" action="" method="post"> ...

Implementing a function in ReactJS that is activated by multiple buttons

Apologies for the unclear title. My issue revolves around having three different button tags, each of which should send a unique argument to the function selectSupplier(). However, no matter which button is clicked, only the last value ("ultramar") is be ...

Angular 2 - Circular dependencies leading to the error message "unexpected value undefined"

Currently, I am organizing my app using shared, features, and core modules. The structure of my SharedModule appears as follows: @NgModule({ declarations: [ TendanceNotePipe, ColorNotePipe, ], exports: [ CommonModule, FormsModule, ...