Creating a reusable function for making HTTP requests in Angular

I have a scenario in my controller.js where I need to make an HTTP GET request when the page loads and when the user pulls to refresh. Currently, I find myself duplicating the $http code. Is there a way to refactor this for reusability? I'm struggling to move it to my services.js file and call it from my controller to execute.

.controller('GamesCtrl', function ($scope, $http) {
  function fetchData() {
    $http(
      {
        method: 'GET',
        url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
        headers: {
          'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
        }
      }).
      success(function (data) {
        $scope.data = data['results']['collection1'];
      });
  }

  // Initial call
  fetchData();

  $scope.doRefresh = function() {
    fetchData()
    .finally(function() {
      $scope.$broadcast('scroll.refreshComplete');
    });
  };
})

Answer №1

To simplify the process, create a private function:


.controller('GamesCtrl', function ($scope, $http) {
  var loadData = function() {
      $http(
      {
          method: 'GET',
          url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
          headers: {
              'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
          }
      }).
      success(function (data) {
          $scope.data = data['results']['collection1'];
      }).finally(function() {
       $scope.$broadcast('scroll.refreshComplete');
     });;
  };

  $scope.doRefresh = function() {
    loadData();
  };

  loadData();
})

For a more comprehensive approach, consider moving it to a service:


.service('KimonoSvc',function($http) {
    return {
      get: function() {
         return $http(
         {
             method: 'GET',
             url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
             headers: {
                 'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
             }
         });
      }
    };
})
.controller('GamesCtrl', function ($scope, KimonoSvc) {
  var fetchData = function() {
    KimonoSvc.get().
         success(function (data) {
             $scope.data = data['results']['collection1'];
         }).finally(function() {
          $scope.$broadcast('scroll.refreshComplete');
        });
  };
  $scope.doRefresh = function() {
    fetchData();
  };

  fetchData();
})

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 sharing a variable with an external JavaScript file in ASP.NET

Utilizing the variables from default.aspx.cs within the script of the default.aspx file has been achieved successfully with the following code: public partial class default: System.Web.UI.Page { public string _file = string.Empty; public string _i ...

Vue JS i18next: Handling Single Translation String Fallbacks

Recently, I've been utilizing i18next, and I decided to set a fallback value for some translated strings in case they are not available in the selected language. Here's an example: en: base.json "yes": "yes" "no": "no" fr: base.json ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Exploring the capabilities of Jasmine testing with AngularJS's $locationChangeSuccess event

I'm trying to figure out the best way to test this code snippet. How would you suggest writing a test for it? $scope.$on('$locationChangeSuccess', function () { $(".modal-backdrop").removeClass('modal-backdrop' ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

AngularJS selection controls: checkbox and dropdown menus

Can someone provide an example that includes a dropdown menu and checkboxes? The options in the checkbox list should match the data in the dropdown. Once a value is selected from the dropdown, the corresponding checkbox option should be automatically chec ...

The issue of the DNN ModuleID not being effectively communicated from the code behind to the ascx component is

Background: I am utilizing a DNN (DotNetNuke) content management system to support VB.NET/Angular1 modules. Currently, I am facing an issue where a value in the code-behind is not accessible in the View.ascx of my module, resulting in a critical runtime e ...

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

Is there a way to display a button and text upon hovering over an image without using JQuery?

On my current WordPress project, I am faced with the task of creating a gallery that displays text and a button when users hover over an image. I have attempted to use a:hover but have only been able to make limited modifications. Can anyone provide guid ...

Encountering Webpack issues following the transition to Next 13

Since updating Next to version 13, we've encountered issues with our application not building properly. It appears that webpack is having trouble with imports, exports, and potentially typescript. ../../libs/queries/src/lib/groq/searchFaq.ts Module pa ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

Execute the controller function once all asynchronous calls to the Angular service have finished

I have integrated the Angular Bootstrap Calendar using a custom cell template and cell modifier. Within my controller, I need to retrieve configuration data from a service that is required by the cellModifier function before it is executed. (function() { ...

What is preferable: defining JSON schema properties or utilizing oneOf conditions within an array of objects

I am looking to represent a variety of objects in a schema through an array called contents. This array can include any number of elements, but they must fall into one of two categories: one type represents text while the other type represents images. Up ...

Adjusting the focus of an element with jQuery based on coordinates and offset values

jQuery.fn.getCoord = function(){ var elem = $(this); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); ); return { x, y }; }; This custom jQuery funct ...

Tips for receiving alerts on external updates to a mongo collection using sails

Currently, I am in the process of creating an application utilizing mongo and sails. As part of my development, I am investigating how the real-time update feature in sails functions. Although I am currently using sails 0.9.16, I am also curious about ans ...

React-Native error message: Promise rejection unhandled - React child cannot be an object

I am experiencing an issue with rendering a list from an array of objects that have the structure provided below. While I have successfully handled the promise and set the data to the state, I keep encountering an error specifically with this array. The da ...

"Exploring the functionality of Vue JS2 checkboxes within a parent and

I am working with a complex nested list structure: <ul> <li v-for="subregion in continents"> <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}< ...

The XMLHTTPRequest Access-Control-Allow-Origin allows cross-origin resource sharing to

I am attempting to send a request to a PHP file. I collect the longitude and latitude from a function in the Maps API, then use AJAX to store these points in a MySQL database. Using AJAX function savePoint(latitude, longitude){ $.ajax({ ...

Using Spring Boot and AJAX to dynamically load content as users scroll down the page

Hi there! I've been running into some issues with Spring Boot and AJAX. Currently, I have buttons that need to be clicked in order to navigate to another page (next, previous). I'd like to use an AJAX request instead to load my page when scrollin ...