Best practices for handling http requests in each individual route of AngularJs

Just starting out with AngularJs and attempting to set up multiple routes with different $http requests. I'm facing an issue where the page content loads late after a route change. I've come up with a workaround, but I feel like there might be a better solution out there. Any advice would be appreciated.

Note: Using AngularJs version 1.6 and ui router.

main.js

var asTwl = angular.module('asTwl', ['ui.router']);

asTwl.controller('generals', function($scope, $http, $timeout){

    $scope.pageLoader = false;

    $scope.getPageData = function(path, postData, obj){
        $scope.pageLoader = true; 
        $http({
            method: 'post',
            url: path,
            data: postData,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        .then(function(response) {
            if (response.data) {
                $scope.data[obj] = JSON.parse(response.data);
                $timeout(function(){
                    $scope.pageLoader = false;
                }, 100)
             }
        })
        .catch(function(e) {
            new Error('Error: ', e);
            throw e;
        })
    }
});

asTwl.controller('homePage', function($scope, $http){   
    var postData = {
      //data...
    }
    $scope.getPageData('path', postData, 'home')
})

asTwl.controller('singlePage', function($scope, $http, $stateParams){   
    var postData = $stateParams;
    $scope.getPageData('path', postData, 'page')
})

asTwl.controller('categoryPage', function($scope, $http, $stateParams){   
    var postData = $stateParams;
    $scope.getPageData('path', postData, 'category')
})

asTwl.config(function($stateProvider, $urlRouterProvider, $locationProvider){

    $urlRouterProvider.otherwise('/');

    $stateProvider
    .state('home', {
        url: '/',
        templateUrl : 'templates/pages/home.html',
        controller : 'homePage'
    })
    .state('info', {
        url: '/info/:id',
        templateUrl : 'templates/pages/info.html',
        controller : 'singlePage'
    })
    .state('category', {
        url: '/category/:type/:id',
        templateUrl : 'templates/pages/category.html',
        controller : 'categoryPage'
    })
});

Appreciate any guidance you can provide!

Answer №1

To start, make sure to encapsulate your calls to services using $http. Then, consider utilizing the resolve concept explained in more detail at https://github.com/angular-ui/ui-router/wiki#resolve

Update

For example, let's see a scenario (without wrapping to service):

$stateProvider
.state('home', {
    url: '/',
    templateUrl : 'templates/pages/home.html',
    controller : 'homePage',
    resolve: {
       routeData:  function($http){
        return $http({
        method: 'post',
        url: 'path',
        data: postData /* your POST data - i don't know what is it for your code*/,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded'               }
        })
     }
    }
})
.state('info', {
    url: '/info/:id',
    templateUrl : 'templates/pages/info.html',
    controller : 'singlePage'
})
.state('category', {
    url: '/category/:type/:id',
    templateUrl : 'templates/pages/category.html',
    controller : 'categoryPage'
})

Then, in the controller:

asTwl.controller('homePage', function($scope, routeData){   
      $scope.someData = routeData;
})

Answer №2

To start, it is advisable to develop a service that will handle communication with the Server/API for manipulating data. Within this service, you can implement the method getPageData, which returns a promise object.

Service Implementation

app.service('myService', function($http){
   var self = this;
   self.getPageData = function(path, postData){
        return $http.post(path,postData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' });
        .catch(function(e) {
            new Error('Error: ', e);
            throw e;
    });
});

Subsequently, you can make use of the resolve functionality within the state configuration of ui-router to ensure that the application waits for the completion of the AJAX call before proceeding.

.state('info', {
    url: '/info/:id',
    templateUrl : 'templates/pages/info.html',
    controller : 'singlePage',
    resolve: {
       getData: function(myService) {
          return myService.getPageData('path', {}, 'info')
       }
    }
})

Answer №3

To summarize, the way your routes need to be updated is as follows:

.state('category', {
    resolve: {
       data : ($stateParams, dataService) => dataService.getData('path', $stateParams, 'category')
    },
    url: '/category/:type/:id',
    templateUrl : 'templates/pages/category.html',
    controller : 'categoryPage'
})

Furthermore, make sure to refactor the getData method to the service (dataService)

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

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Is It Better to Consider Angular Elements as Building Blocks or Encapsulated Components?

When it comes to using element directives, I have noticed Angular element directives being used in two distinct ways: 1. Block Level Components In this approach, the element is styled with display:block, essentially making the element itself the componen ...

Create a copy of an element without altering the original

Currently, I am attempting to create a duplicate of a class and ensure that it remains unaffected when the original is altered. So far, I have tried: $(".newclass").addClass("oldclass"); However, this method does not copy the content. var _elementClone ...

Is there a way to transfer textbox value to ng-repeat in AngularJS?

1) The Industry dropdown menu corresponds with a code textbox. Depending on the selected industry, the code will change accordingly. 2) There is a dynamic feature to add or delete Movie Names and Directors' names. In this table, there are three colu ...

User interface failing to refresh after fetching data with AJAX

I have been working on a restaurant app and here is the code snippet: // Select date and load resources $scope.selectDate = function (date) { $scope.dateInActiveSelection = date; loadMenuFor(date); }; // Load daily menu fo ...

Can you place more than one Twitter Bootstrap carousel on a single webpage?

Latest Version of Twitter Bootstrap: 2.0.3 Sample HTML Code: <!DOCTYPE html> <html dir="ltr" lang="en-US" xmlns:og="http://opengraphprotocol.org/schema/"> <head> <link rel="stylesheet" type="text/css" media="all" href="reddlec/style. ...

Angular 1.3.10 encountered error: [$injector:modulerr] - Uncaught Exception

The application currently has limited content, resulting in this basic error. The use of ui-router is causing the issue. Here are the code snippets from different files: app.module.js: 'use strict'; angular .module('app', app); ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Ways to dynamically update CSS properties (such as changing the color scheme throughout the entire application)

I have a question... If you're interested in conditional styling, the best approach is to utilize either ng-class or ng-style. However... For instance, let's say I'm an admin and I would like to customize the color of my application using ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

Ways to change the color of a button when it is clicked?

I am attempting to change the color of a button on another button click, but it doesn't seem to be working. function show_col(){ console.log("hello"); var path=localStorage.getItem(".physics_section #color1 button"); $(''+ ...

Propagating changes in child scope variables to parent scope in AngularJS

Is there a way to efficiently update variables in the ParentCtrl when a new variable is created in the ChildCtrl? Without relying heavily on $on and $watch functions for an easier implementation. ParentCtrl ChildCtrl / ChildCtrl2 / ChildCtrl3 / ChildC ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Regulation specifying a cap of 100.00 on decimal numbers entered into a text input field (Regex)

I have created a directive that restricts text input to only decimal numbers in the text field. Below is the code for the directive: import { HostListener, Directive, ElementRef } from '@angular/core'; @Directive({ exportAs: 'decimal ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...

What is the process for incorporating dynamic templates in AngularJS?

I have created 3 unique templates (DetailView, CardView, Column) for displaying content on a single page. Users can easily switch between these views. My goal is to display only one view at a time on the page. When the user switches views, I want to remov ...

When should we utilize the React.Children API in React applications?

Exploring the potential use cases of the React.Children API. The documentation is a bit confusing for me (Using React v.15.2.0). https://facebook.github.io/react/docs/top-level-api.html#react.children According to the documentation, this.props.children ...