Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add call back for $resource methods in AngularJS

It could be a common case that we need to show an error/success message to the user after he updates/creates some data, how can we implement it in AngularJS?
I want to add callbacks but could not find a solution. Using $http.post().success().error() works, but I wonder if I can do it with the higher lever API $resource.
Or, we should write directives or use $watch()?
Thanks for your help in advance.

like image 481
Edward Avatar asked Dec 13 '12 03:12

Edward


People also ask

What is callback function in AngularJS?

Callback function is a function which is passed to a function as parameter and is executed when the outer function is completed. Callbacks are a feature of JavaScript not particularly angularjs. Its a way to send a function as a parameter to the callee so that the callee call that function once the task is finished.

What is $resource in AngularJS?

$resource documentation describes it as: A factory which creates a resource object that lets you interact with RESTful server-side data sources. $resource is most powerful when it's configured with a classic RESTful backend.

What is angular resource in AngularJS?

AngularJS $resource is a service that lets you access RESTful web services in a way that is more Angular-friendly. $resource takes care of serializing and deserializing data for you to focus on the application logic. Moreover, AngularJS $resource provides functions to communicate with RESTful APIs.


2 Answers

Actions from the Resource class can be passed success and error callbacks just like the lower level $http service

From the docs

  • HTTP GET "class" actions: Resource.action([parameters], [success], [error])
  • non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

Non-get actions are prefixed with $.

So you can do this

User.get({userId:123}, function(u, getResponseHeaders){   // this is get's success callback   u.abc = true;   u.$save(function(u, putResponseHeaders) {     // This is $save's success callback, invoke notification from here   }); }); 

Edit: here's another example from a previous plunker. The get request will fail since it request a non existing json file. The error callback will be run.

someResource.get(function(data){     console.log('success, got data: ', data);        }, function(err){     alert('request failed'); }); 
like image 125
jaime Avatar answered Oct 07 '22 01:10

jaime


With latest AngularJS versions, you could have a look to the $interceptors which are part of the $httpProvider.

Then you can intercept ALL the requests before beeing sent or after the response.

angular.module('app').config(function($httpProvider){    $httpProvider.interceptors.push(function($q) {     return {       'request': function(config) {         console.log('I will send a request to the server');         return config;        },        'response': function(response) {         // called if HTTP CODE = 2xx          console.log('I got a sucessfull response from server');          return response;       }        'responseError': function(rejection) {         // called if HTTP CODE != 2xx         console.log('I got an error from server');         return $q.reject(rejection);       }     };   });  }); 

Note that you have to return config or response to get it working.

In the case of rejection, you need to return a deferred rejection, to get the $http.get().error() still working after the interception.

like image 39
M'sieur Toph' Avatar answered Oct 07 '22 01:10

M'sieur Toph'