Implementing a specific block of code once an Angular service successfully retrieves data from the server and finishes its operations

Within the service:

appRoot.factory('ProgramsResource', function ($resource) {
    return $resource('Home/Program', {}, { Program: { method: 'get', isArray: false } })
});

Inside the controller:

appRoot.controller('ProgramCtrl', function ($scope, ProgramsResource) {
    $scope.searchPrograms = function () {
        $scope.Programs = ProgramsResource.get(
            {
                Name: $scope.searchProgramName,
            });
    };

    $scope.SortBy = "Name";
    $scope.searchPrograms();

    //The code below is intended to run only after searchPrograms() is completed
    $scope.TotalItems = $scope.Programs.TotalItems;
    $scope.ItemsPerPage = $scope.Programs.ItemsPerPage;
});

The function searchPrograms(); is used for fetching data from the server. The lines of code following $scope.searchPrograms(); should be executed afterwards:

$scope.TotalItems = $scope.Programs.TotalItems;
$scope.ItemsPerPage = $scope.Programs.ItemsPerPage;

However, instead of waiting for searchPrograms() to finish its operation, the code beneath it is getting executed. This is a common behavior in JavaScript where it does not pause for AJAX calls to complete before moving on to the next lines. To ensure that certain code executes only after an AJAX call is finished, callbacks are used in JavaScript and promises are commonly employed in AngularJS for this purpose.

I came across an insightful article about Angular promises but am struggling to understand how I can implement promises in my specific scenario.

Answer №1

If you want to include a callback function as a parameter in the ProgramResource.get method, you can follow this example:

   $scope.retrievePrograms = function () {
        $scope.ProgramList = ProgramResource.get(
            {
                Name: $scope.searchProgramName,
            }, function () { 
                $scope.TotalItems = $scope.ProgramList.TotalItems;
                $scope.ItemsPerPage = $scope.ProgramList.ItemsPerPage;
            });
    };

Answer №2

Utilize the $q and deferred promise in order to achieve something similar to this:

 $scope.searchPrograms().then(function(data) { // data represents the data returned by the search programs

   $scope.TotalItems = $scope.Programs.TotalItems;
   $scope.ItemsPerPage = $scope.Programs.ItemsPerPage;

 }

Ensure that the searchPrograms function returns a promise.

        var deferred = $q.defer();
        var callback = function (response) {
            if(response.error) {
                deferred.reject(response.error)
            }

            deferred.resolve(response);
        };

        //Invoke your service call that requires a callback like myService.request(callback);

        return deferred.promise;

Thus, once the request is completed, the code will be executed within .then(function(data) {

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

Tips for utilizing React.GA.plugin.require with multiple trackers:

Can you help me figure out how to enable the ecommerce plugin with multiple trackers using the react-ga package? This is the code I've been using to initialize the trackers: const initTracker = (trackerId, name) => ({ trackingId: trackerId, g ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Adding null at the end of a JSON encoded PHP array

During the debugging process, this is the data being sent to my javascript: header("Content-Type: application/json"); //echo json_encode($full_product_list); echo json_encode(array()); Below is my ajax call: jQuery.get( "non public api sorry ") ...

Checking if a phone number begins with a zero using a regular expression

Is there a way to ensure that numbers entered into a field always start with a 0? Initially, I thought the company wanted to mandate entering 0 first, but I believe there might be a more elegant solution. function validateNumber(dataValues, setErrors) ...

ReactJS issue: Violation of the Invariant

I have recently started working on an exciting project using React JS and I have been enjoying the process so far. However, I recently encountered an error that has been causing me some trouble. Here is the error message I received: Uncaught Error: Invari ...

Encountering a circular structure while attempting to convert to JSON -- starting at an object created by the 'HTMLInputElement' constructor

I have been trying multiple solutions to fix this issue, but I'm still struggling to resolve it. My application is built using Next.js and I am using axios as the HTTP client. import React, {useState} from 'react' import axios from 'axi ...

Exploring the process of extracting a nested JSON value using Postman

I am currently facing an issue with parsing the json response from a post request, and then sending the parsed data to a put request. Here is the response body: { "createdBy": "student", "createdOn": "2019-06-18", "Id1": "0e8b9 ...

Using Node JS to retrieve JSON data from index.html upon button click

I'm currently learning the ropes of Node.js and want to set up a server where users can navigate to http://localhost:8000/ and be directed to index.html. In that file, there's a button to access JSON data. I plan to download this JSON data onto m ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Using Selenium with C# to find elements within a chart

I am trying to locate and interact with the stimulusFrequency circles on this chart so that I can click and drag them. <svg class="svg-graph-content graphEventHandler ng-valid" ng-model="hearingGraph" viewBox="0 0 470 355" preserveAspectRatio="none"> ...

JavaScript bug with URL encoding in Internet Explorer 11

I am encountering an issue with Internet Explorer 11 (IE 11) when attempting to call a JavaScript URL function. The problem lies with the URL parameter value, which is in Unicode format but the result displays as ????? instead of Unicode characters. Belo ...

Make sure to adjust the original router URL when the application is being run within iframe or object

Currently, I am embedding Vue apps within object tags or iframes of a master Vue app container. Initially, I set up a file server that serves the container or the requested sub-app to render inside a div. Below, I will show the necessary routing of my Nod ...

Initiate data extraction immediately upon the DOM being fully loaded using NightmareJS

Currently, I am utilizing nightmarejs and facing a challenge that I am struggling to resolve. After using the goto(URL) command, I then proceed to use the evaluate() command to execute specific operations on the webpage. However, I have noticed that while ...

Tips for making a DIV span the entire width of a page when it is within a column with the Bootstrap class 'col-md-6'

I'm having a little trouble arranging divs next to each other on a page. Specifically, I want to ensure that if there is only one instance of the col-xs-12 col-md-6 div class on the page, it should take up the full width (100%) instead of just 50%. Th ...

Creating a user-friendly HTML form to convert multiple objects into JSON format

Edited content: $.fn.serializeObject = function() { var obj = {}; var arr = this.serializeArray(); $.each(arr, function() { var value = this.value || ''; if (/^\d+$/.test(value)) value = +value; if (obj[this.name] !== u ...

Oops! The file or directory you are looking for does not exist. Please check the location and try again

This is the content of my server.js file: var express = require('express'), app = express(); app .use(express.static('./public')) .get('*',function (req,res) { res.sendfile('/public/main.html' ...

The cursor remains positioned below the video within the designated div

I'm currently facing an issue in a project where the cursor div I created stays underneath the video element. No matter what I do, I can't seem to bring it to the front. Even setting a z-index on the video tag hasn't helped. Can someone plea ...

Guide on displaying an X mark on a checkbox in AngularJS when the ng-disabled value is set to true

Is there a way to display an X mark in red on checkboxes when the ng-disabled condition is evaluated as true? I am a beginner in Angular.js and would appreciate any assistance. Here is what I have attempted so far: if (module.Name === 'val1' || ...

AngularJS $scope.$watch doesn't detect changes when the input box is cleared

Recently, I delved into AngularJS and encountered a challenge while attempting to share data between two ng-controllers within the same ng-app module using a factory. Surprisingly, the data (HTML input field) from controller1 mostly gets shared with contro ...