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.
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.
$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.
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.
Actions from the Resource class can be passed success and error callbacks just like the lower level $http service
From the docs
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'); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With