Dealing with errors in AngularJS factory servicesTips for managing errors that occur

Factory code

app.factory('abcFactory', function ($http, Config, $log) {
    var serviceURL = Config.baseURL + '/results';
    return{
        results:function() {
            var promise = $http({
                method: 'GET',
                url: serviceURL,
                timeout: Config.httpTimeout
            }).then(function(response) {
                    return response;  

                },  function(reason) {
                    $log.error("Request Failed: ", reason)
                });

            return promise;
        }
    }
});

Controller code

app.controller('abcController',function ($scope, $log,abcFactory, Config)
{

        abcFactory.results(function(data){
            $scope.results =data;
        },function(response)
        {
          console.log("response"+response);

          if(response.status === 0)
          {
              console.log("gotcha");
               $scope.serviceTimedoutError(response.data, response.status, response.config);
          } else
          {
                console.log("gotcha");
                $scope.serviceFailure(response.data, response.status, response.config);
          }


        });
});

$scope.results loads correctly when the service returns a successful response.

If there is an error, the error message from the factory's log stating "Request Failed: blah blah" can be seen on the console.

The problem: Despite an error occurring, I am not receiving the error message in the controller, and "gotcha" is not even being printed in the browser console. I need to retrieve error details in the controller so that I can display them in the view. I prefer not to pass $scope in the factory.

What could be wrong with my Controller code?

I believe I am following a similar approach as outlined in AngularJS Failed Resource GET, but I am not achieving the desired outcome.

Answer №1

It seems like you are aiming for the results function to accept callbacks, however it is currently missing any arguments in its parameter list. Despite this, you are still returning a promise.

To rectify this issue, you have two options:

abcFactory.results()
  .success(function() { ... })
  .error(function() { ... })

Alternatively, you can update the results function itself:

results: function(successCallback, errorCallback) {
  var promise = $http(...).success(successCallback).error(errorCallback);
  return promise;
}

Answer №2

Important Update: Please be aware that the $http legacy promise methods 'success' and 'error' are now deprecated. It is recommended to utilize the standard 'then' method instead. If the setting $httpProvider.useLegacyPromiseExtensions is set to false, attempting to use these deprecated methods will result in a $http/legacy error.

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 the best method for setting a session cookie securely while also using CSRF tokens?

In my express application, I am working on setting the session cookie to be secure. Here is the code snippet I have tried so far: app.use(express.cookieParser()); sessionOptions = definitions.REDIS; sessionOptions.ttl = definitions.session.expiration; app ...

Select a color at random from the array, animate it, then repeat the process by selecting a new random color from the

Currently, I am utilizing gsap and three js to animate a light source. I have an array containing various colors that I would like to cycle through randomly during the animation process. My objective is to continuously loop through the random color selec ...

Unusual behavior: Django app not triggering Ajax XHR onload function

I'm currently working on a Django app that features user posts, and I'm in the process of implementing a 'like' / voting system. Initially, I set up this functionality using complete page refreshes combined with a redirect after the vot ...

What are the most effective methods for enhancing this perspective?

I currently have a functional view that I would like to enhance for better optimization. It is currently quite convoluted and I am unsure of the best approach to simplify it. Should I use functions in the controller or create a directive? The main area ...

Implementing Pagination in Vue: How to Make it Work with Response Data

I am looking to integrate pagination from the response data into my existing code, while also incorporating filters. JavaScript var entriesList = new Vue({ el: "#post-list-template", data: { posts: [], categories: [], cu ...

Personalize Tooltip on Highchart Area Chart

I am currently in the process of customizing the tooltip for my area chart using Highchart. Within this area chart, I have plotted 3 series. My goal is to display the tooltip at a fixed location on the chart's top center. When hovering over any point ...

URL not functioning properly on Django CMS menu

After setting up django-cms and creating a collapsible menu with categories and subcategories, I encountered an issue. When clicking on a main category, the URL appears correct but it does not navigate to the corresponding page. Main categories without chi ...

Form fields will not automatically populate with link parameters; the user must manually input the information

My form fetches data from the database using server-side code when the user inputs the "user_id" field. The User ID field is the primary field on the form, and when the user enters their user ID, all other fields retrieve the corresponding user data from t ...

Please upload JSON data into a database using Node.js

As a beginner in learning node.js, I have embarked on my "Hello World!" project. The premise is simple - I am requesting a JSON file from the server via an API and receiving a response that looks like this: { "files": [{ "url": "http://auction ...

JavaScript (Create a button that toggles the visibility of an element)

I have implemented a hamburger menu that transforms into an x when clicked. I am looking to modify it so that clicking on the hamburger opens the menu, and clicking on the x closes the menu. Below is the code I have been working with: <!DOCTYPE html&g ...

Run an npm script located in a different package

Imagine I have two node packages, one named parent and the other named child. The child package contains a package.json file with some scripts. Is it viable to merge the scripts from child into the context of parent? For instance: child/package.json: "s ...

Adjust the Scope in Angular-Charts.js Post-Rendering

I am currently facing a challenge with displaying multiple charts using the angular-charts.js framework. The issue is that I require all the charts to have the same scale, but each chart currently has its own scale based on the displayed data. Unfortunatel ...

The functionality of Jquery autocomplete _renderItem appears to be malfunctioning

There seems to be an issue with the _renderItem function as it is not executing at all. I even tried using console.log to debug but no messages are being printed. I also attempted using various attributes like 'autocomplete', 'ui-autocomplet ...

Strip away the HTML tags and remove any text formatting

How can I effectively remove HTML tags and replace newlines with spaces within text? The current pattern I am using is not ideal as it adds extra space between words. Any suggestions on how to improve this pattern? replace(/(&nbsp;|<([^>]+)> ...

Prevent deletion of already uploaded images in Blueimp by disabling the delete button

After using the blueimp upload script to upload files, I noticed that the file information is saved in a data table along with the upload timestamp. However, when I go to edit the form, the files reappear. The simple task I want to achieve is disabling th ...

Managing Nested Elements in State in ReactJS

Check out the code snippet below: import React,{useState} from 'react' const iState ={ Name : '', Email :'', Salary :0, Error:{ EName:'*', EEmail:'*', ESalary:'* ...

Need to capture click events on an HTML element? Here's how!

I am attempting to capture click events on an <object/> element that is embedding a Flash file This is the approach I have taken so far: <div class="myban" data-go="http://google.com"> <object class="myban" data="index.swf>">< ...

Hiding elements in FireBase and Angular based on user identification

Currently venturing into the world of Firebase in conjunction with AngularJS after previously working with php and server-side rendered pages. I am grappling with how to securely hide specific parts of an application from certain users. I have three disti ...

Developing an npm console application that is "installable" similar to tools like yeoman, gulp, or grunt

Recently dipping my toes into the world of NPM, I've been itching to create a package that functions as a console app (think gulp and grunt). My goal is simple: I want users to be able to run npm install -g mypackage followed by mypackage This sh ...

Tally the number of words entered in the text box

Is there a way to make the keyword search in a text area live, rather than requiring the user to manually initiate the search? I have a working code that counts the number of times a specific keyword is used within the text, but it currently requires the u ...