function declarations for success and error handling within the service's controller

Here is the code snippet for a service that includes a fetchData function being called from a controller.

In the Service:


app.service("geturl", function($http) {
    urllist = [];
    geturl.fetchData = function() {
        var data = [];
        for (i = 0; i < urllist.length; i++) {
            (function(index) {
                return $http.get(geturl.urllist[index], {
                    timeout: 8000
                })
                .then(function(response) {
                    data[index] = response.data;
                });
            }(i);
            return data;
        });
    };
});

I need to handle the success and error functions of $http.get in the controller to be used in the UI. How should I approach this?

Answer №1

When it comes to writing the success and error functions for $http.get in the controller...

The usual way is to use the .then() function with two function arguments - the first as the success handler, and the second as the error handler.

$http.get(url,options).then(function (response){
    //success handler function
    },function(error){
  //error handler function     
  })

Alternatively, you can also define the .success and .error functions separately.

$http.get(url,options).success(function (response){
    //success handler function
    }).error(function(error){
  //error handler function     
  })

A tip: Instead of returning something directly from your service's geturl method and defining callbacks there, it's better practice to return a promise from the service itself.

   ... 
   app.service("geturl",function($http){
     ...
     getData:function(){
        return $http.get(url,options);
     }
     ...               
   });
   ...

Then, handle the success/error callbacks in the module where you are using/consuming the service.

geturl.getData().success(function(){
//handle success
}).error(function(){
//handle error
})

And remember, when dealing with multiple http requests, avoid using for loops. Since everything is asynchronous, it's important to use tools like AngularJS's $q service for handling such scenarios effectively. Check out @pankajparkar's answer for more insights.

Answer №2

It appears that you are looking to retrieve data once all ajax requests have finished. One way to accomplish this is by utilizing the $q.all() method.

Data Retrieval Service

app.service("getData", function($http, $q) {
    this.dataList = [];
    this.fetchData = function() {
        var data = [], promises = [];
        
        for (i = 0; i < dataList.length; i++) {
          (function(index) {
            var promise = $http.get(getData.dataList[index], {
              timeout: 8000
            })
            .then(function(response) {
              data[index] = response.data;
            });
            
            promises.push(promise); // add promise to array
          }(i);
        };
        
        return $q.all(promises).then(function(resp){ 
            return data; // return data after all promises have completed
        });
    };
});

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

String representation of a failed test

While working on some coding exercises on codewars, I came across a simple one that requires creating a function called shortcut to eliminate all the lowercase vowels in a given string. Here are some examples: shortcut("codewars") // --> cdwrs shortcut ...

Utilizing jQuery to incorporate a radio input function in a POST request

When the Index.php page button is pressed, data is sent to the Resultx.php script page, which then responds with an asynchronous call back on the same Index.php page. index.php <script> $(document).ready(function() { $("#input_form").subm ...

React hook form submit not being triggered

import React, { useState } from "react"; import FileBase64 from "react-file-base64"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import { TextField, Select, Input ...

Encountered an unexpected symbol < in JSON while implementing fetch() operation

I'm currently working on linking my React signup page to my Django API in order to automatically create a user profile in Django when a user signs up. Whenever I attempt to create a new user, I encounter this error in my console: Signup.js:33 ...

Synchronize one file between numerous applications

I manage a handful of small web applications for a small team at my workplace. These apps share a similar layout and file structure, with many files being identical across all of them. For instance, the index.js file in the src/ directory is consistent in ...

Using Selenium in Java, one can wait for a JavaScript event (such as onchange) to finish before proceeding

When a group of interconnected input fields have an onchange event, the values in some fields are updated correctly while others are not due to interference from the onchange event. Once the onchange event is triggered on a field, it initiates a process t ...

When the onInput event is triggered, React renders components and console.log() displays different values

When I type in the input field, it triggers the onInputChange() function. This function updates the state of inputValue, and then calls the getValue() function which retrieves the current state of inputValue and logs it to the console. However, the value d ...

Issue with Twilio's sendMessage function: it is not successfully delivering messages to every value within

I am encountering a problem with Twilio failing to send a message to all the values in an array. var index; var a = req.body.numbers; console.log(a); if (req.body.numbers.indexOf("undefined") > -1) { console.log("No numbers stored"); } else { for ...

Identifying when a page-loading or reloading event has been canceled

When the Cancel button is pressed during page load/reload, the content of the page loads partially. Is there a more effective way to address this issue rather than displaying incomplete content? For instance, consider showing a message such as "Page load ...

What are some ways to manipulate JSON data following a successful AJAX request?

I've been grappling with this issue for quite some time now, trying various methods without any success. I won't bore you with the details of my failed attempts, but instead, I'll show you the code I'm currently working with. Here' ...

Await the sorting of intervals

Looking for a solution to re-execute a hand-made for loop with a delay of 10 seconds after it finishes indefinitely. I've attempted some code, but it keeps re-executing every 10 seconds rather than waiting for the loop to finish before starting again. ...

Click on an element that is nested within another element that can also be clicked on

I'm facing a challenge while attempting to create an accordion inside another accordion. The issue arises with the nested elements and their behavior upon clicking. Essentially, I have a parent div with the class .applicant, which expands on click by ...

Having trouble retrieving Yelp Fusion using an express backend

Attempting to retrieve Yelp data within my backend using Express and then saving the data in the state for frontend use has presented a challenge. When making the request, an error is thrown displaying AxiosError: Request failed with status code 400 in the ...

Using the Node.js mongodb-native library to insert multiple strings as separate documents

node: 8.9.4 mongo: 3.6.3 mongodb-native: 2.2.33 Query: How can I seamlessly insert an array of simple strings as new documents with just one call? I prefer not to pre-process the array before insertion. I'm in search of a magical mongo solution h ...

Managing styles and scripts in Asp.Net MVC: A guide to efficient organization

Currently, I am utilizing asp.net mvc 2.0 in my projects and appreciate its design and functionality. However, I find that it lacks proper support for applications with a significant amount of styles and scripts. To address this issue, I implement areas, ...

The error message "Cannot set headers after they are sent to the client" is indicating that the headers have already been sent to the client and

What could be causing this error to appear? It seems like the only route available is through post method. I can't seem to find any other place where a header is being sent. I'm also puzzled as to why body.content is showing up as undefined, ev ...

What steps can I take to prevent the audio from disappearing while utilizing `Tone.PolySynth()` along with the `Sequence` method?

Background I've been experimenting with creating a step sequencer using Tone.js. Instead of the traditional method of playing MP3 files with "Players," I decided to use "PolySynth" to achieve different sound variations, inspired by Jon Oliver's ...

JavaScript Enhanced Sticky Navbar

Hey there! I've been working on creating a sticky navbar using vanilla JavaScript. My goal is to make the logo and navbar stay sticky when scrolling, but unfortunately, I'm running into some errors that I can't seem to fix. I would really ap ...

Is it possible to concurrently run two instances of ReactI18Next within a single application?

I'm currently attempting to implement 2 separate instances of React-i18Next within the same application. My goal is to have certain parts of the app translated with instance1 and other parts with instance2. I've familiarized myself with createIn ...

Understanding the utilization of memory in the Chrome task manager

My investigation into a memory leak in a large JavaScript app, running as a widget in a browser with webkit and sfx (JavaScript core engine), led me to discover that the source of memory increase over time was $.ajax(..). I experimented with different ver ...