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

The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only ...

Is there a way to export a specific portion of a destructuring assignment?

const { a, ...rest } = { a: 1, b: 2, c: 3 }; If I want to export only the rest object in TypeScript, how can I achieve that? ...

Kendo UI Web - MultiSelect: choosing an option multiple times

Currently, I am encountering an issue with the Kendo UI MultiSelect widget when trying to select an option multiple times. An example of this is shown in the image below where I want to choose Schindler's List again after selecting The Dark Knight. Ho ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

The variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

What could be causing the delay in loading JSON data on my HTML page?

I have developed my controller to accept JSON data in Wordpress: app.controller('AboutController', function($scope, $http) { $scope.device=device; var page_id = 2; $.ajax({ url: 'http://davidemilone.com/provawp/?json=get_page& ...

Obtain Data for Visualizing Graph with JSON within a Database-connected Graph (highchart.js)

In the process of creating a database-driven graph, I am utilizing libraries from Codepen. These libraries include: THIS and Highchart.js The HTML file on display simply showcases the chart, while the main data processing is handled in an index.js file t ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

How is it possible to encounter a missing semicolon CssSyntaxError during a Gatsby build?

Currently, I am in the process of developing a Gatsby page with Material UI. The design of the page is almost finalized; however, upon completing the project, an unexpected build error occurs when running npm run build. WebpackError: Pathname: /invitation/ ...

Implementing AJAX in Rails for the new/create action can greatly enhance the user

I have a timeline with event sections on it that allow you to create, view, update, and delete events directly on the timeline page. Currently, the functionality for deleting an event is working smoothly as the delete section refreshes along with the timel ...

Passing data between child components using Vuejs 3.2 for seamless communication within the application

In my chess application, I have a total of 3 components: 1 parent component and 2 child components. The first child component, called Board, is responsible for updating the move and FEN (chess notation). const emit = defineEmits(['fen', 'm ...

Customizing React components based on API data

const LinkList = () => { const [links, setLinks] = useState([]); const url = 'http://localhost:5000/xyz'; const hook = () => { console.log('effect'); axios .get(url) .then(respo ...

Exploring the compatibility between ADFS 2.0 and JSONP

My main website uses passive federation (ADFS 2.0) and includes javascript that communicates with an MVC Web API site using jsonp. I am facing a challenge in getting this WebAPI to support Single Sign On on the same machine but different port. The passive ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Is it possible for the filter with the new date() function to accept formats other than yyyy-mm-dd?

After receiving a response from mydatepicker in the specific format below: { "isRange":false, "singleDate":{ "date":{ "year":2022, "month":5, "day":13 }, "jsDate": ...

Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation? Below is the code snippet that has be ...

How to Redirect Multiple URLs Simultaneously using Laravel

Upon clicking a button, the user will be redirected to generate a PDF in a new tab and simultaneously redirected back to the dashboard as well. ...

Unregistering an event with AngularJS

Exploring the functions of a controller named MyCtrl: class MyCtrl { constructor($scope, $rootScope, ...) { this.$scope = $scope; this.$rootScope = $rootScope; this.doThis = _debounce(this.resize.bind(this), 300); ... ...

On Windows systems, where exactly does npm place its packages during installation when using Node version 10.x

Does anyone know where I can locate the locally installed npm modules when using NodeJS version 10? I have checked under C:\Users\MyUser\AppData\Roaming, but I cannot find the "npm" folder. ...