Utilize $http.get within a service/factory to retrieve a set of items

I am trying to utilize a http.get promise within an angularjs service, perform some manipulation on the retrieved collection, and then pass it back to a controller...

My query is regarding the proper usage of $http.get() in a service to fetch and modify the result prior to sending it back to the controller. Below is an example code snippet showcasing what I am looking for: The PEN code

var app = angular.module('myApp', []);

app.controller('customersCtrl', ['$scope','customer',function($scope, customer) {
  $scope.odds = customer.odds;
}]);

app.factory('customer', ['$http', function($http) {
  var all = [{'Id':88, 'Name':"A"}, {'Id':89, 'Name':"ShoutNotBeHere"}]; 
  var odds = [];

  $http.get("http://www.w3schools.com/angular/customers.php")
    .then(function(response) {
      all = response.records;
    });

  angular.forEach(all, function(c, i) {
    if (i % 2 == 1) {
      odds.push(c);
    }
  });

  return {odds: odds};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
  <div ng-app="myApp" ng-controller="customersCtrl">
    Odd ids from www.w3schools.com/angular/customers.php
    <ul>
      <li ng-repeat="c in odds">
        {{ c.Id + ', ' + c.Name }}
      </li>
    </ul>
  </div>
</body>

Answer №1

Essentially, you have the ability to modify the data within the ajax success call and then return that updated data from the success function. However, in order to return data from the ajax success, utilizing a promise pattern is necessary to return the data from the $http.get method. You must return the object from the promise of $http.get, and within the .then function of $http.get, you can manipulate the retrieved data as needed.

Factory

app.factory('customer', ['$http', function($http) {
    var all, odds = [];
    var getData = function() {
        return $http.get("http://www.w3schools.com/angular/customers.php")
        .then(function(response) {
          all = response.records;
          angular.forEach(all, function(c, i) {
            if (i % 2 == 1) {
              odds.push(c);
            }
          });
          return odds
        });
    }
    return {
        getData: getData 
    };
}]);

Controller

app.controller('customersCtrl', ['$scope','customer',function($scope, customer) {
    customer.getData().then(function(response){
         $scope.odds = response;
    });
}]);

Answer №2

I have made some adjustments to your code so that it now returns a promise from the factory. This allows you to set the value as soon as the promise is resolved.

var app = angular.module('myApp', []);

app.controller('customersCtrl', ['$scope','customer',function($scope, customer) {
  customer.then(function(data){
    $scope.odds = data.odds;
    customer.then(function(data){
      console.log(data);
    });
  });
}]);

app.factory('customer', ['$http', function($http) {
  var all = [{'Id':88, 'Name':"A"}, {'Id':89, 'Name':"ShoutNotBeHere"}]; 
  var odds = [];
  return $http.get("http://www.w3schools.com/angular/customers.php")
    .then(function(response) {
      all = response.data.records;
      angular.forEach(all, function(c, i) {
      if (i % 2 == 1) {
        c.Id = i;
        odds.push(c);
      }
    });
    return {odds: odds};
  });
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
  <div ng-app="myApp" ng-controller="customersCtrl">
    Odd ids from www.w3schools.com/angular/customers.php
    <ul>
      <li ng-repeat="c in odds">
        {{ c.Id + ', ' + c.Name }}
      </li>
    </ul>
  </div>
</body>

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

What is preventing me from being able to access a property within my function?

In the post method below, I am trying to access baseUrl. However, it is showing undefined. Can you help me understand why and provide a solution? const API = { baseUrl: "http://my_api_address", post: (path, payload) => { let headers = { ...

Ensure that the control button is pressed during the JavaScript onclick event function

I am looking to create a JavaScript function that checks if the CTRL button is pressed. Here is my PHP code: <tr class="clickable" onclick="gotolink('<?= base_url() . invoices/createinvoice/' . $customer->Id; ?>')"> And here ...

In ReactJS, when you encounter TextField values that are "undefined", it is important to handle them appropriately

I'm a beginner when it comes to ReactJs and Material-UI, so please bear with me if my question seems silly. Currently, I have a file named Main.js which includes the following code snippet: handleChange = (name, event) => { if(event==null) ...

Exploring AngularJS unit testing: integrating async and await with Jasmine

I'm currently facing a challenge with unit testing my Angular service using the async/await keywords in the respective (Jasmine) unit tests below. The test for the built-in Promise is functioning correctly, however, I am encountering difficulties in g ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

To reveal the secret map location, just tap on the button - but remember, this only applies to

I am encountering an issue with duplicating a card and toggling the hidden location map. Currently, the location button only works for the first card and not for the rest. I need each card to independently open and hide the location map when clicked on the ...

Error message: The md-autocomplete function is throwing a TypeError because it cannot read the property 'then' of an undefined object

I am encountering an issue with the md-autocomplete component from angular material. Here is my code snippet: <md-autocomplete required md-search-text="searchTxt" md-selected-item-change="setModelValue(item.name)&q ...

In the absence of a value

In my code, I've implemented a functionality that saves the user's input into local storage and displays it in a specific ID. However, I want to make sure that if the input field is left empty, the user is prompted to enter their name. function ...

Can a component be passed as props and utilized within a child Component in Vue.js?

If we have components A, B, and C in a Vue 2.0 app, A declares, registers, and uses B. Can we pass C from A to B? For example: <template> <div class="A"> <B :child_component="C" /> </div> </template ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Anticipating the fulfillment of promises with the power of Promises.all

I have adopted the code found here for loading multiple .csv files. Upon successful loading of these files, my intention is to then render a react component. Below is the method located in datareader.js that I am currently working with. I am exploring the ...

Troubleshooting the order of Javascript execution in bundled TypeScript applications

I encountered an issue with the execution order of generated JavaScript code during bundling, resulting in an error message when everything is bundled together. An error occurred: [$injector:nomod] Module 'app.demo' is not accessible! This cou ...

ng-click seems to have foresight of modifications prior to $scope being updated

Encountering a recurring issue where passing properties on $scope through an ng-click is necessary to access the property within the ng-click method, but $scope.rejectionMessage never seems to update. Here's a snippet of the HTML structure: <lab ...

The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates. I suspect that the canvas, which is ove ...

Troubleshooting: Issues with accessing object properties in a function in AngularJS

In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below: $http.get('js/data.json').success(function(data) { $scope.locations = ...

"Encountering a 404 error when submitting a contact form in Angular JS

Looking to set up a contact form for sending emails with messages. Currently diving into Angular Express Node Check out the controller code below: 'use strict'; /** * @ngdoc function * @name exampleApp.controller:ContactUsCtrl * @descripti ...

Matching objects in an array based on a specific property using the key of another object

To display information in the UI based on matching values between the data.examples array object's name.value property and the keys in the wcObject.notCoveredList, we need to create a logic. If there is a match, all corresponding values from wcObject ...

How can we efficiently trigger a function that sends an axios request by leveraging data from a v-for loop?

Currently, I am developing an e-commerce platform using Rails and VueJS. In order to display the orders of a specific user, I have created a component file. Within this component, I am utilizing a v-for loop to iterate over and showcase all the information ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...