Callbacks for successful and failed responses when using AngularJS $resource

I've written a simple code snippet that's functioning as intended, but I'm looking to incorporate success and error callbacks. Here's the current code snippet:

angular
    .module('studentInfoApp')
    .factory('Student', Student)
    .controller('StudentsController', StudentsController)
    .config(config);

function config($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'StudentsController',
        templateUrl: 'app/views/student-list.html'
    })
}

function Student($resource) {
    return $resource('/students');
}

function StudentsController(Student, $scope, $http) {

    Student.query(function(data) {
        $scope.students = data;
    });

}

In the function Student(), it simply returns the resource without allowing me to specify success and error callbacks using .then for example. Is there something obvious that I'm overlooking? Appreciate any insights you might have! Thank you!

Answer №1

Check out this potential answer:

FetchData.students(function(info, headers) {
  // Success
  $scope.studentInfo = info;
}, function(error) {
  // Error
});

Alternatively, here's another approach using promises directly:

FetchData.students().$promise.then(function(result) {
  // Successful
  $scope.studentInfo = result.data;
}, function(error) {
  // Unsuccessful
});

Answer №2

When utilizing angular $resources, you have the option to store the query directly into your variable. This variable will contain the promise and once the data is returned, it will hold the actual data.

If you want to manage success and error scenarios, you can simply use the stored promise and include success and error callbacks as shown below:

$scope.students = Student.query();
$scope.students.$promise.then( function(response) {
     console.log('Request successful');
}, function (error) {
    console.log('Error occurred');
});

Answer №3

Successfully resolved the issue, however, I am open to any suggestions for improvement. Below is the updated code:

function StudentsController(Student, $scope) {

    Student.query(function(data) {
        $scope.students = data;
    })
    .$promise.then(function successCallback(response) {
        console.log('success');
    }, function errorCallback(error) {
            console.log('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

Phaser encountering a null window.computedStyle() error in Firefox (while dealing with a hidden Iframe)

I'm experiencing issues with Phaser game-engine games crashing specifically in Firefox. The error that keeps popping up is related to a hidden iframe containing the game, which is hidden due to a pre-game video ad being displayed. I keep getting a ...

The use of jQuery ajax requests is leading to a refresh of the page

I've encountered an issue with a button on my HTML page that is not associated with any form. <input type='button' id='submitter' value='add'/> There is a click handler attached to it: $('#submitter').c ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

Attempting to execute Backand.signup() resulted in the failure of the task titled "Create My App User"

Attempting to sign up a new user with the following code: Backand.signup(firstName, lastName, username, password, password2); Results in the following error: POST https://api.backand.com/1/user/signup 504 (GATEWAY_TIMEOUT) Upon checking the logs (Log & ...

What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked. However, there ar ...

Angular dropdown component with intricate object

Looking for some guidance on working with a select element within an Angular application I'm developing. If we take a look at the code snippet below, what would be the most effective approach to updating the 'childId' property of each item ...

What is the best way to halt a jQuery function when hovering over it?

Currently, I have a jQuery function set up to run on setInterval(). However, I am looking for a way to pause the interval when hovering over the displayed div and then resume once no longer hovering (i.e., continue cycling through the divs). Does anyone ...

The Angular HTML Autocomplete feature is not functioning as intended when hosted on a CDN in Chrome, despite setting it to "nope" or "off"

When setting Autocomplete to "nope" or "off" in my input box for surname, I'm still able to select from the autocomplete list. This issue occurs when accessing our Ui app through CDN at link [https:// Xyz. net], but works correctly when accessing it d ...

Leveraging flot in conjunction with NPM, React, and Node

I've been attempting to utilize flot in a Node.js React project, but I'm running into issues with the import. The browser console is showing the error: Uncaught TypeError: _jquery2.default.plot is not a function This error is essentially the sa ...

What is AngularJs's preference: URL or ID for templateUrl?

When looking at the AngularJS documentation, you will come across an example using the templateUrl property: In the HTML: //ngApp... <div ng-controller="Ctrl"> <div my-customer></div> </div> And in the controller: . ...

JavaScript: Dynamic animation of a DIV element based on conditions

I am looking to create an animation for a DIV layer when another div is clicked. However, I only want the animation to play if the DIV layer has not been animated yet. My initial thought was to check the height value, as I am animating the height of the d ...

Unlocking the JSON data for a specific id through an onClick event

Using axios to fetch data from an API and display it is working perfectly fine for me. Now, I am trying to extract each value and show the returned data when I click on a "TableRow" element. This is the JSON data I am dealing with: https://i.sstatic.net/T ...

Tips to prevent the return of undefined when a condition is not satisfied

I'm currently working on a react app and I have an array of objects (items) that I want to iterate over in order to display each object based on its index. I am using useState to set the index, which is updated when the user clicks a button. const ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

Tips for creating a custom Menu with content overflow in a single direction

What is the goal of this task? I have developed a custom Menu in my application with 8 options. There is a need to dynamically disable certain menu options based on specific conditions (e.g. disabling the last 4 options). When a user hovers over a disable ...

eslint is designed to not handle multiple package.json files

There are two package.json files in my project root folder └ app ---- /public └ /styles └ /src └ package.json └ eslintrc.json └ webpack.config.js └ server - /something └ /something ...

What could be the reason for the 'if' statement not being assessed in the 'then' promise of the ajax request?

I'm facing an issue with an ajax call in my code. I have a 'then' promise set up to handle errors, where the console log returns false correctly when there is an error. However, for some reason, the if condition in the next line is not being ...

Exploring the idea of how a Node.js server works

Although I have a good understanding of jQuery, I am new to modern JavaScript frameworks that have been introduced in the past few years. In the example provided, I can see how index.html functions and how server.js handles requests from it. However, I am ...

Steps for verifying the existence of a function in a instantiated controller during unit testing with Jasmine

I am new to unit testing a controller in AngularJS and I am facing a challenge. I am trying to test whether the login function in the controller is calling the correct service. However, I am getting an error that the function doesn't exist in the cont ...