What is the most effective way to load data prior to the controller being loaded

Is there a way to fetch data from a service before the view and controller are loaded? I need assistance with this.

resolve: {
            getAlbum: function(albumService){
                return albumService.getAlbums();

        },getAtum: function(albumService){
                return albumService.getAtum();

        }

    }

I am working with a service that looks like this:

.factory('albumService', ['$http', '$q'],
    function albumService($http, $q) {
        // interface
        var service = {
            albums: [],
            getAlbums: getAlbums,
            getAtum:getAtum
        };
        return service;

        // implementation
        function getAlbums() {
            var def = $q.defer();

            $http.get("data.json")
                .success(function(data) {
                    service.albums = data;
                    def.resolve(data);
                })
                .error(function() {
                    def.reject("Failed to get albums");
                });
            return def.promise;
        }

             function getAtum() {
            var def = $q.defer();

            $http.get("data.json")
                .success(function(data) {
                    service.albums = data;
                    def.resolve(data);
                })
                .error(function() {
                    def.reject("Failed to get albums");
                });
            return def.promise;
        }
    })

I want to receive data from the service before initializing the controller and view.

.controller('PlaylistsCtrl', function($scope) {
  $scope.playlists = [{
    title: 'Reggae',
    id: 1
  }, {
    title: 'Chill',
    id: 2
  }, {
    title: 'Dubstep',
    id: 3
  }, {
    title: 'Indie',
    id: 4
  }, {
    title: 'Rap',
    id: 5
  }, {
    title: 'Cowbell',
    id: 6
  }];
})

I am fetching data from two services and would like to display a loader until both sets of data are retrieved. To achieve this, I am using:

http://ionicframework.com/docs/api/service/$ionicLoading/

Plunker: http://plnkr.co/edit/4k7fliaYQx3teVH326cD?p=info

Answer №1

After being resolved, the resolve properties are automatically injected by ui-router.

.controller('PlaylistsCtrl', function(albums, atum) {
    // 'albums' and 'atum' are now resolved and can be used
})
  1. I suggest using albums and atum directly instead of getAlbum and getAtum as they represent the actual data.
  2. The usage of defer is incorrect. $http.get already returns a promise, and it's recommended to use then instead of success and error.

    return $http.get().then();

Easiest example in this jsbin.

Answer №2

If you're looking to display a loading spinner on a page until its content is fully loaded, you can achieve this with the following code snippet:

  resolve: {
        apiData: "albumService",
        itemDetailsData: function($q, apiData) {
          console.log("Turning on Spinner...")
          var items = apiData.getAlbums();
          if (items) {
            console.log("Turning off Spinner...")
            return $q.when(items);
          } else {
            return $q.reject();
          }
        }
      }

In your controller, make sure to inject itemDetailsData as a dependency.

I hope this solution helps!

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 way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

I'm curious if anyone has had success utilizing react-testing-library to effectively test change events on a draftJS Editor component

​I'm having trouble with the fireEvent.change() method. When I try to use it, I get an error saying there are no setters on the element. After that, I attempted using aria selectors instead. const DraftEditor = getByRole('textbox') Draf ...

"Learn how to use JavaScript and jQuery to alphabetically sort the default td values in a table

This table and script are being used to alphabetically sort the data within the td tags: <button type=button>Sort Options</button> <table class="table-data"> <tr> <td class="filename">C</td> </tr> <t ...

Using the data from two input fields, an ajax request is triggered to dynamically populate the jQuery autocomplete feature

I've been struggling with this issue for quite some time now. My goal is to pass 2 arguments (the values of 2 input fields in a form) in my ajax call so I can use them for a jQuery autocomplete feature (the search is based on a MySQL query using the v ...

What is the best way to retrieve elements from this JSON data?

Currently, I am developing a command line interface to display random quotes. I have found an API to fetch quotes from, but the issue is that the JSON response is returned as an array. [{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate ...

Focused on individual characters in a string to implement diverse CSS styles

Is there a way I can apply different CSS classes to specific indexes within a string? For example, consider this string: "Tip. \n Please search using a third character. \n Or use a wildcard." I know how to target the first line with CSS using : ...

The custom directive validator is taking too much time to call the REST API, causing a delay in setting form.$invalid and

My input text field has a custom directive that triggers a REST Web Service Api call using $http (Restful Resource) and usually takes around 500ms. However, there is a chance that the user might submit the form before the call returns. How can I prevent th ...

What is the best way to resize a PDF to match the width and height of a canvas using

I need help with a project involving rendering previews of PDF documents in a UI similar to Google Docs. {documents.map((doc) => { return ( <div key={doc.id} className=" ...

A type error was thrown: $.ajax function does not exist within another function

I encountered a persistent ajax error on the website. Error : Uncaught TypeError: $.ajax is not a function at Hei Here is my code for reference: Can anyone pinpoint where I may be going wrong? The suggested solutions from other sources have not resol ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

What is the best way to execute two asynchronous calls sequentially in JavaScript?

When using a common generic function for AJAX calls, the initial request retrieves all data from the server and maintains it within local scope. However, subsequent requests are still hitting the server, even when the data is already available locally. Thi ...

Tips for creating read-only checkboxes with multipledropdown.js in Angular.js

I am trying to make all checkboxes in a multiple dropdown list readonly using Angular.js with the multipledropdown.js plugin. My code snippet is as follows: <div class="col-md-6" ng-show="sub_sub_menu"> <div class="input-group bmargindiv1 col-md- ...

Is there a way to automatically update the state in ReactJS whenever new information is added or deleted, without the need to manually refresh the page

I have encountered an issue that I have been trying to resolve on my own without success. It seems that the problem lies in not updating the Lists New state after pushing or deleting from the API. How can I rectify this so that manual page refreshing is no ...

What is the best way to synchronize the scale of images with the tempo of a song?

I just started learning CSS, JS, and HTML and I have a question about scaling an image based on a song. Despite searching through YouTube and various forums, I still haven't found a solution. Any help would be greatly appreciated :) Here is the HTML ...

Tips for implementing the handleClick method within a class component, as opposed to using the export default function syntax in

Hey there! I'm a beginner in React and I'm trying to incorporate Material UI into my project. I came across the documentation for the menu section like this, but I'm facing some challenges with writing my code. Specifically, I'm struggl ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

Creating dropdown options within a DataGrid in Form.IO: A step-by-step guide

I'm currently working with the Form.IO JS library to develop a new form. Within this form, I need to include a DataGrid containing 11 components. To ensure all components fit inline, I have applied the CSS rule overflow: auto (overflow-x: auto; overfl ...

The function is not defined, even though it is located within the same file

I've encountered an issue with my web page where I'm trying to read data from an HTML data table and update it on a PHP file using AJAX queries in JavaScript. Everything was working fine until recently, even though I didn't make any signific ...

What is the best way to utilize a function that is housed within a service?

I am facing an issue where I need to access a function globally across controllers. The problem arises when trying to use the function defined within a service in another function. An error is thrown stating that the function cannot be found. Even after at ...