Tips for preloading data before showing the page using AngularJS and Restangular

I have been incorporating AngularJs and Restangular with a PHP backend. Currently, I am utilizing a function that is triggered by the route (detail/list) to retrieve data from Restangular and store it in a variable.

However, the challenge arises when there is a delay in establishing a connection with the database - the page appears blank initially, and then after a brief delay of 2-3 seconds, the data finally populates and displays.

This issue persists when navigating between the details and list pages.

Answer №1

One way to handle data before the page loads without a blank screen is by using the 'resolve' function:

The 'resolve' function executes before the view is rendered.

$routeProvider.when('/admin/task/:id' , {
    templateUrl: '/app/task/admin-task-results.tpl.html',
    controller:'AdminTaskDetailsCtrl',
    resolve: {
        task: function($route, Restangular) {
            return Restangular.one('tasks', $route.current.params.id).get();
        }

    }
});

You can then pass the resolved object (in this case 'task') as an argument to your controller:

module.controller('AdminTaskDetailsCtrl', function ($scope, task) { ... });

It's worth noting that this approach may not always be ideal as it delays user feedback when changing routes. It may be better to load data in the controller and show a spinner until the data is available.

Answer №2

If you are waiting for data to be loaded before drawing the view, you can utilize the following method in the controller constructor to initially render the view without the data and then load the data later:

$scope.$on('$viewContentLoaded', function(){
  // Load data into model here
});

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

Are Json files a reliable choice for storing data in Next.js applications?

I'm currently working on developing a video application that will offer both free and premium videos. With approximately 100 videos in the pipeline, I am contemplating whether setting up a database to store video links is necessary. Considering securi ...

Transitioning from AngularJS to Flux: Embracing the React methodology

Having extensive experience with AngularJS, I am eager to understand the shift in mindset required when transitioning to writing web apps using Flux and React. Avoiding the Flux+React vs Angular debate that is already saturated online, my focus is on iden ...

Is it possible for attribute directives to utilize transclusion?

I am interested in implementing slotted transclusion and have come across examples of element directives that look like this: <my-directive> <slot-a></slot-a> <slot-b></slot-b> </my-directive> I am wondering if ...

Controlling API requests using JavaScript, Python, and Bash

If I had to choose a language: Python (using Selenium or any other tool) Javascript (with node and any module) Bash (using curl for example) I would need to: Make a request to an API (Scrapy cloud) to retrieve a specific value, in this case, I only ne ...

Turn off automatic play on the spotify software development kit

I have successfully integrated the web playback SDK of Spotify into my website, allowing users to log in via their Spotify accounts and play music. However, I am facing an issue where the music starts playing as soon as the page is loaded. I would like th ...

The functionality of the Bootstrap4 accordion is not functioning according to my expectations

My goal is to create a unique e-commerce checkout page design. Each panel would be opened sequentially, with the next panel unfreezing when the action button of the current panel is clicked. However, I seem to be making a mistake as it is not working as in ...

The servlet is successfully receiving a JSON post, but unfortunately, it is not being displayed

Currently, my focus is on JAVA programming. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("TEST TOMCAT SERVLET"); S ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

Facing issues connecting index.js to the database in React and unable to resolve the problem

After creating a frontend for users to submit movie reviews to a database, I am now attempting to connect a MySQL database that I set up to the index.js file. My goal is to have the database populated with the first entry. I am working on achieving this by ...

Tips on presenting messages to users after clicking the submit button?

I am trying to extract data from a table. I am unsure if my current code is able to retrieve the value from the table. <script> function validateForm() { var x = document.forms["assessmentForm"]["perf_rating11"].value; var y = document.f ...

Tips for triggering the API call only when a change is detected

#In the provided code snippet, the useEffect hook is being used to fetch data from an API using the apiData() function. The data retrieved consists of objects with properties such as id, name, parent name, and isActive. The isActive property is linked to ...

Is Joi's existence a myth?

I've been using Joi for validation, and I've encountered a situation that I'm having trouble with. I have an object that sometimes includes an id field (for editing) and other times it doesn't (for creating). My goal is to validate tha ...

Angular-Foundation Multi-Level Off-Canvas Menu: A Unique Navigation Solution

I am attempting to implement multi-level off-canvas menus using angular-foundation. However, the issue I'm facing is that whenever a submenu link is clicked, the entire menu closes instead of displaying the submenu. The code I am using is based on th ...

Come together with Array starting from the specified startIndex and ending at the

I'm curious to know if there is a utility function available that allows for joining arrays while also providing an index. Perhaps Prototype or jQuery already have this feature, but if not, I am willing to create it myself :) What I envision is somet ...

How can you use ui.router to set up one controller as the child of another controller?

To create a nested controller in html, you can simply write the child controller inside the parent controller like this: <div ng-controller="parentCtrl"> <div ng-controller="childCtrl"> When using ui.router, you can specify one state as a c ...

tips for efficiently loading JSON files using Angular

I currently have a situation where multiple controllers are calling the method getData() from a service. To prevent unnecessary duplicate http calls for the same json file, I have implemented the following approach: QuizApp.service('quizService' ...

In Node.js, when using the `new Date(year, month, date)` constructor, the date is automatically converted to UTC

var dateInCST; //Obtaining the current date in CST time zone. /*Trimming the time portion and retaining only the date.*/ var onlyDateInCST = new Date(dateInCST.getUTCFullYear(), dateInCST.getUTCMonth(), dateInCST.getUTCDate()); console.log(o ...

Imitate a HTTP request

Currently, I am working on developing a front-end application using Angular (although not crucial to this question). I have a service set up that currently supplies hard-coded JSON data. import { Injectable } from '@angular/core'; import { Obser ...

Setting up Babel to effectively function across multiple directories

I've been utilizing Babel for some time now and it effectively transforms my ES Next code to the dist directory using this command: babel src --out-dir dist --source-maps --copy-files Up until now, all my JavaScript code has been stored in the src fo ...