Executing processes individually within AngularJS

Just making sure I understand correctly, I have a simple web service resource query function set up like this

//Get country lists
$scope.getCountry = function(){
    $http({
        method  : 'GET',
        url     : cdnLinks('country'),
    }).success(function(data) {
        $scope.countries = data;
    }).error(function(data) {
        console.log(data);
    });
};

//Get profile 
$scope.getProfile = function(profile_id, select){
     var formatJSON = {
            profile_id: profile_id,
            select: select,
        };
    var json = JSON.stringify(formatJSON);
    var urlsafe = exEncrypt(json);
    ProfileService.profileActions.query({payload:urlsafe}).$promise.then(function(datas){
        $scope.uProfile = datas[0];
        document.querySelector('title').innerHTML = $scope.uProfile.username;
    });  
};

//Initialize update sequence
$scope.initUpdate = function(profile_id, select){
    $scope.getCountry();
    $scope.getProfile(profile_id, select);
}

Essentially, when a user clicks the "Update" button, the

ng-click="initUpdate(param1, param2)"
function is triggered to load and display all necessary information. This function works well, but there is a problem. Due to getCountry() typically returning a larger file size [~3 - 3.5kb, load time ~260++ms server dependent] compared to getProfile() [~1 - 2kb, load time ~200++ms server dependent], the profile may be displayed before the country list is fully loaded, resulting in some empty fields on the UI page.

To address this issue, initially I tried applying a timeout to getProfile() like this

$scope.initUpdate = function(profile_id, select){
    $scope.getCountry();
    $timeout(function(){
        $scope.getProfile(profile_id, select);
    }, 200);
}

While this workaround worked temporarily, I found it challenging to determine the exact amount of delay needed as it depends on the server's loading time.

I am interested in exploring alternative approaches to ensure that

  1. All necessary resources are fully loaded and COMPLETE (getCountry(), getInterest(), getABCDEFG(), and other similar functions...)
  2. Only the getProfile() function is executed?

Answer №1

To achieve this, you can utilize promises by integrating $q from AngularJS (https://docs.angularjs.org/api/ng/service/$q) into your controller. By incorporating promises in getCountry() and initUpdate(), you can ensure that the program waits for the completion of the getCountry() request before proceeding. Additionally, if there are other requests to include, $q.all() can be used to wait for multiple requests to finish before displaying the profile.

$scope.initUpdate = function(profile_id, select){
    $scope.getCountry().then(
        function(){
            $scope.getProfile(profile_id, select);
        }
    );
}

$scope.getCountry = function(){
    var deferred = $q.defer();
    $http({
        method  : 'GET',
        url     : cdnLinks('country'),
    }).success(function(data) {
        $scope.countries = data;
        deferred.resolve();
    }).error(function(data) {
        console.log(data);
        deferred.reject();
    });

    return deferred.promise;
};

(Note: It may be possible to enhance the code by directly returning the $http promise)

Answer №2

To prevent certain parts from appearing, consider implementing loaders.

Create a boolean variable to control when the loader should be displayed based on the status of the call.

If you need to load data before the view loads, check out ui-router and its resolve properties.

You can also return the $http call in your functions to handle it as needed (such as chaining them).

//Retrieve list of countries
$scope.getCountry = function(){
    return $http({
        method  : 'GET',
        url     : cdnLinks('country'),
    });
};

//Retrieve profile data
$scope.getProfile = function(profile_id, select){
     var formatJSON = {
            profile_id: profile_id,
            select: select,
        };
    var json = JSON.stringify(formatJSON);
    var urlsafe = exEncrypt(json);
    return ProfileService.profileActions.query({payload:urlsafe}).$promise  
};

//Initialize update sequence
$scope.initUpdate = function(profile_id, select){
    $scope.getCountry().success(function(data) {
        $scope.countries = data;
        $scope.getProfile(profile_id, select).then(function(datas){
           $scope.uProfile = datas[0];
           document.querySelector('title').innerHTML = $scope.uProfile.username;
        });
    }).error(function(data) {
        console.log(data);
    });
}

This approach should work, but feel free to adapt it to suit your needs and preferences.

If you have any further questions (especially regarding ui-router), don't hesitate to ask.

EDIT :

Normally, $http calls are not placed in controllers but in services.

Below is an example of defining a state (from ui-router) with resolves :

$stateProvider
  .state('mystate', {
    url: "myroute"
    templateUrl: 'template.html',
    controller: "mystateController",
    resolve : {
        countries : function($http){
                           return $http({
                           method  : 'GET',
                           url     : cdnLinks('country'),
                        });
                    }
    }
  })

You can then inject the resolve parameter into your controller :

app.controller('mystateController', function(countries) {
  //Access the retrieved countries here.
  console.log(countries);
});

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

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...

JavaScript: Creating keys for objects dynamically

const vehicles = [ { 'id': 'truck', 'defaultCategory': 'vehicle' } ] const result = [] Object.keys(vehicles).map((vehicle) => { result.push({ foo: vehicles[vehicle].defaultCategory }) }) c ...

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

Troubleshooting the issue of JavaScript not executing on elements with a specific CSS class

I am attempting to execute a JavaScript function on each element of an ASP.NET page that is assigned a specific CSS Class. Despite my limited knowledge of JavaScript, I am unable to determine why the code is not functioning properly. The CSS Class is being ...

Is there a way for me to automatically go back to the home page when I press the back button on the browser?

My ecommerce website has a shopping cart page where customers can purchase products and make payments. After the payment is completed, they are directed to a thank you page. The flow of the website is as follows: Home page => Products => Shopping ca ...

What is the best way to arrange this object alphabetically by name using Angular?

My client is in need of an AngularJS application that will interact with an API from an existing app. The API returns JSON data structured like the following: { "groups":{ "60":{ "name":"History" }, "74":{ "n ...

Error code 403 is returned when attempting to send an ajax Post request, indicating

While my code runs smoothly on localhost using a WAMP server, I encountered a 403 (forbidden) error after transferring it to a shared hosting environment. My first attempt was: $.post('login.php?login', { user_email: user_email, user_password: u ...

When utilizing the header slot in v-data-table, an empty header row is unexpectedly appearing

Having an issue with adding an extra empty row when using the header slot in v-data-table from Vuetify2. Check out the codepen here: https://codepen.io/satishvarada/pen/rNBjMjE?editors=1010 Vue.component('pivot-table',{ data:()=>({ ...

What criteria does Angular use to determine when the aot compiler should be utilized?

This page discusses the concept of modules in Angular and explains the two approaches to bootstrapping - dynamic and static. The configuration for these approaches is typically found in main.ts: // Using the browser platform with a compiler import { platf ...

"Utilizing the splice method to insert an element at specified indexes within an

const list = [] const obj = { name: '', mobile: '' } _.forEach(errors, (value, key) => { // eslint-disable-next-line no-debugger // debugger const field = key. ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

JavaScript string: Use regex to find and replace with position index

I'm not very familiar with regex, so I'm curious about the process of replacing a section in a string based on a regex pattern where the index is part of the identified section. Let's consider this example string: let exampleStr = "How do ...

Alternative method for handling web requests in case JavaScript is not enabled

Issue: i) I am developing a JSF2 application and need to implement a tab control on a page. When a user clicks on a tab, the content for the panel below should be loaded from an xhtml file on the server using an ajax call. ii) I want this functionality ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Having issues with passing POST data during file handling operations

I am attempting to utilize Ajax POST on my WordPress website to check if checkboxes are selected and update their values in the database upon clicking a button. Although using the standard PHP form submission is the simplest method, the fields that I need ...

Adding the tasksMap to the dependency array in the React useEffect hook will result in an endless loop

I'm facing an issue with adding tasksMap to the useEffect dependency array, as it causes an infinite loop. Can someone guide me on how to resolve this? To ensure that the user sees an updated view of tasks that are added or modified, I need the app to ...

AngularJS - Showing only items belonging to the same team

Currently, I am attempting to filter out all objects that belong to the same team. Each object is structured as follows: {"first_name":"Bob","last_name":"Sagat","username":"bobsagat", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...