The async function defined in the angular.run() method did not run prior to the controller being executed

Recently, I've been experimenting with Angular and struggling to figure it out. The issue I'm facing is with running a $http method in app.run(). This method fetches rooms from the server and initializes it in $rootScope.rooms. However, in the controller, when I try to access this rooms variable, it sometimes returns null because the $http method is asynchronous and the controller loads before it finishes. I'm exploring alternative ways to handle this situation.

game.js

angular.module('GameModule', [])
.run([function ("injectors...") {
    $http.get("/rooms").success(function(result){
        $rootScope.rooms = result;

    }).error(function(error){
        console.log('Error fetching rooms');
    });
}])
.controller('GameCtrl', ['$scope', function ($scope) {
    console.log($rootScope.rooms);  
}]);

Since the rooms variable will be used in other files as well, I prefer not to place the $http method inside every controller unless there are no other options. It would be ideal if I could utilize a service in Angular for this purpose.

Answer №1

AngularJs follows asynchronous behavior by default when making REST calls. If you prefer a more organized or synchronous approach, you can utilize "promises" ($q service in AngularJs). Below is a snippet of code to demonstrate this:

Service code (to be used):

app.lazyload.factory('myService',['$http','$q', function($http,$q) {

        return{
            showAll :function ()
            {
                var deferred = $q.defer();
                $http.post('rest/getAll?cd='+ (new Date()).getTime())
                .success(function(data)
                {
                    deferred.resolve(data);
                })
                .error(function(data)
                {
                    deferred.reject(null);
                    console.log("in error block");
                });

                 return deferred.promise;
            }
        };

    }]);

Controller code (to call the service):

function showAll()
                {
                    var promise = myService.showAll();

                    promise.then(function success(data) {
                        $scope.allitems = data;
                        console.log(data);
                        console.log('$scope.allitems'+$scope.allitems[0].name);

                    }, function error(msg) {
                      console.error(msg);
                    });

                };

I have made revisions to my answer. Putting the call showAll() at the start of the controller body will load the data during initialization, as per your request. This approach will yield the desired outcome.

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

Performing an AngularJS $http POST request with a combination of JSON parameter and query string

I'm currently trying to write an AJAX call using Angular's $http object in order to send a post request with JSON in the body and a query string appended to the URL. Despite going through the documentation for $http, looking for solutions on SO, ...

The passport local strategy functions properly when tested with Postman, but encounters a "missing credentials" error when used with axios

I am currently working on creating a login system using passport and a local strategy. Strangely, when I attempt to send the request through axios it doesn't seem to work, although it functions properly with Postman. When using axios, I receive an er ...

Leverage the basename feature in React Router when rendering on the server side

My website is being hosted from the directory /clientpanel on my server, making the URL http://xxx.yy/clientpanel. The client-side code looks like this: const history = useRouterHistory(createHistory)({ basename: "/clientpanel" }); render( <Ro ...

Building a Nested/Tree Structure with an HTML Table Component in Angular.js

Exploring Tree Structure Expand and Collapse Options: The code is currently written using an HTML table. Tackling the implementation with ng-repeat is proving to be a challenge. Here is the data structure for each row: { "id": 1, "name": "Gro ...

Unexpected Issue Encountered in JQuery Integration

I recently added jQuery to my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> After that, I included a link to my JavaScript file: <script src="public/javascripts/new_javascript.js" type ...

Trouble with using .className for form validation

The .className is not applying the formValidation class on getWeight.length < 1 and getHeight.length < 1. I am stuck trying to figure out why this is happening after reviewing the code extensively. Any thoughts on what could be causing this issue? Y ...

Error message: When accessing react-native camera roll, the message "this.state.photos is not a valid object" appears

Encountering an error while attempting to implement camera roll functionality in my demo app. The error states, "null is not an object (evaluating 'this.state.photos')" View iOS Error Message. I am a beginner developer working on my first react-n ...

Obtaining data from an external ng-repeat element

My list contains items that are being repeated using ng-repeat details. I want to be able to hover over one of the li elements and have the background of a div called background (which is outside of the ng-repeat) change to the url of the corresponding d ...

Is there a different option instead of relying on promises for asynchronous requests?

Let's consider a scenario where we have a basic front end application (perhaps using Angular) and a back end app. When the front end app performs a get request, in most cases, the Angular repository will initiate an $http.get request which will return ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

Identifying the conclusion of a folder being dropped in vanilla JavaScript

I am working on determining when a directory tree has been completely traversed after being dropped onto a page. My goal is to identify the point at which the next process can begin once the entire folder and its sub-directories have been processed by the ...

"I encountered an error stating that res.json is not a function while trying to establish a connection between ReactJS

dataset.list.js import React, { Component } from "react"; import Datasets from "./data"; import axios from "axios"; class App extends Component { render() { return <Datasets datasets={this.state.datasets} />; } ...

What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame? var is_array = function (value) { return value && typeof value === 'object&apos ...

Creating tube-like geometry in intervals using three.js

Is there a way in Tube Geometry(Three.js) to plot and render only a portion of the tube at a time, with the option to continue plotting from that point after a set interval or timer? ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

Display a Vue.js div element based on conditions matching a specific variable value

Is it possible for Vue.js to display a div only when a defined variable is set to a specific value? Currently, v-show="variable" can be used to show the div if the variable is set. However, I would like to know if v-show="variable=5" can be implemented t ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

Show the current date and time, and update it whenever the user chooses a different one

I need help with displaying the current date and time within a div, with the seconds refreshing when the page loads and changing when the user selects another date and time from the picker. I'm trying to accomplish this with the following script, but ...

Dragging and Dropping Electron Files into an Inactive Window

I am exploring the implementation of drag and drop functionality within an electron window, utilizing the suggested approach of sandboxing processes. This involves isolating ipcMain from ipcRenderer and creating a bridge through a preload.js script (refer ...

Loop through the API URLs for AngularJS

$http({method: 'GET', url: '/xxx/xxx/xas'}).success(function(data) { $scope.website = data.websites; }); $http({method: 'GET',url: '/xx/xasxxx?websiteId='+$scope.website.websiteId}).success(function( ...