Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in determining the layout of the dashboards. According to my understanding, Angular builds by executing config methods first, followed by run methods, and then the controllers. Unfortunately, $HTTP cannot be used in a config method, so I have incorporated it into my main.js:

    MetronicApp.run(['$rootScope','$http', function($rootScope,$http) {

  var CUID = Cookies("CUID");
  console.log('portlet settings for '+ CUID);
   $http.get('/myurl/V3_portlet_settings?p_user_id='+CUID)
        .then(function(response) {
            console.log(response.data);
            console.log('portlet status: ' + response.status);
            $rootScope.$broadcast("dashSettings",response.data);
        });

}]);

Upon running, everything functions smoothly and I can view the data in the console.

Subsequently, in my controller:

$scope.$on( "dashSettings", 
function(event,data){
    $scope.dData = data;
     console.log('dash data service identified in dash controller');
     console.log($scope.dData.count);
    } );

Now, I have a couple of questions:

  1. Is this the most effective approach for retrieving settings before initializing the dashboard? My intention is to integrate the dash-building calls within my $scope.$on block. I started exploring how to execute a run method synchronously prior to initializing the controllers, but perhaps it's unnecessary.

  2. Any insights as to why the $scope.$on method may not be triggering?

Thank you in advance

Answer №1

One effective strategy is to organize your $http functions within a service or factory and then resolve them in your controller. The use of promises plays a crucial role in this approach, as outlined in Angular's documentation:

A service that helps you execute functions asynchronously and handle their return values (or exceptions) upon completion

To start, create a service like so:

app.factory('DataService', function($http) {
  var getValues= function() {
    var url = '/myurl/V3_portlet_settings?p_user_id='+ CUID;
    return $http.jsonp(url); // returns a promise
  };

  return {
    getValues: getValues
  };
});

Then, utilize the service in your controller:

myApp.controller('MyController', function ($scope, DataService) {     
    DataService.getValues().then( // resolve the promise using .then()
    function(data){
      // success callback
      // now you can safely handle the data in your controller
      console.log(data);
    },
    function(error){
      // error callback
      console.log(error);
    })   
});


Utilizing data services for managing data operations such as $http requests is generally considered a best practice.
The ability to chain promises and effectively manage asynchronous calls via promise return enhances the overall workflow.

Check out John Papa's style guide for further insights, particularly the sections on 'Separate Data Calls' (Y060) and 'Return a Promise from Data Calls' (Y061)

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 best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Guide on retrieving the mouse button press from a command event using XUL

There appears to be a difference between the XUL command and click events. While my function is called when using the command event, the event object does not include the button property. I'm trying to figure out: how can I determine which mouse but ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...

`How can I extract information from the internet?`

I am attempting to retrieve data from the following URL: . My focus is on obtaining the raw data series rather than the data presented in tables and charts. Although the website provides a button for downloading a .csv file, I am unsure of how to automat ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

Modify the main container width based on the size of the table

Would it be possible for the main container width to increase along with the table width? Is that achievable? <div class="container main-con"> <table class="table table-hover"> <tr><td></td></tr> </table> ...

Utilizing HTTPS for OpenWeatherMap API in JavaScript encounters obstruction

I'm currently working on a project with free code camp where I am attempting to create a weather app using the OpenWeatherMap API. However, I have encountered an issue. My project needs to be submitted on Codepen and use HTTPS for geolocation. Due to ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

The Angular multi select tree feature seems to be malfunctioning

I recently incorporated a plugin called angular-multi-select-tree from GitHub into my project. Here is how I added it: First, I installed it via bower using the command bower install angular-multi-select-tree --save. This updated the bower.json file to i ...

``I am experiencing slow loading times with Google Maps JS when using

When accessing Google Maps on Safari, zooming in can be frustratingly slow on both Windows and Mac. The experience feels glitchy, with the zoom starting, freezing, then finally finishing. In comparison, Chrome provides a much smoother and faster zooming ex ...

What causes index.html to be returned instead of app.css?

I deploy my Angular application using an express server. var express = require('express'); var server = express(); server.use(express.static('./app')); server.all('*', function(req, res) { res.sendFile('index.html&apos ...

The prop type 'lg' supplied to 'ForwardRef(Grid)' is not valid and has failed

This particular code snippet is responsible for managing the layout of components on the webpage. However, I have encountered some warning messages in the console: Warning: Failed prop type: The lg prop provided to ForwardRef(Grid) is invalid, it should ...

CanvasJS showcasing a variety of pie charts

I need to generate multiple pie charts for a website, but I'm struggling with the idea of dynamically rendering them based on the required quantity. I know that I will have to create a maximum of 28 pie charts at once. My initial approach involves man ...

Overlay a translucent image on top of another using JavaScript

Is it feasible to overlay a transparent-background image onto another image using JavaScript? For example, if you have a website featuring various product pictures and some of these products are recalled, can you superimpose the Do-Not-Enter sign (circle-w ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

How can I submit a form using ajax and retrieve the data as an array?

Hey there, I need some help on how to submit a form and receive data in the form of an array like this: { "notes":'some notes', "validUntil": '12/12/2015', "status": 1, "menuItemName": "HR Section", "menuItemDesc": "gggg" } Here is th ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

The Google Drive API's `copyfile` function is limited to accessing all files in the drive, even if just a copy operation is needed

I found a way to copy files using this page https://developers.google.com/drive/v2/reference/files/copy. However, it only works when I request permission , allowing me to modify any file in their drive, which is not ideal. My goal is simply to copy a publ ...

React, handling various router navigations

I have set up a BrowserRouter to serve /, /login, and /logout on my website. Once logged in, users can access an app with a consistent navbar on every page and dynamic content that holds data/functionality within the "Main" template component, which utiliz ...