I'm trying to build a simple notification service on angularJS :
angular.module("my.services", [])
.service("NotificationsService", function() {
this.show = function(message, options) {
// display a notification
};
this.error = function(message) {
this.show({...});
}
...
});
That would be fired when the server returns a "notifications" array embedded in the api :
{
notifications: [{type: "error", message: "Error message"}, ...],
data: [item1, item2, ...]
}
And now I would like to plug my service to $http, but I can't find a way to do so !...
Any ideas ?
I'm trying to build a simple notification service on angularJS :
angular.module("my.services", [])
.service("NotificationsService", function() {
this.show = function(message, options) {
// display a notification
};
this.error = function(message) {
this.show({...});
}
...
});
That would be fired when the server returns a "notifications" array embedded in the api :
{
notifications: [{type: "error", message: "Error message"}, ...],
data: [item1, item2, ...]
}
And now I would like to plug my service to $http, but I can't find a way to do so !...
Any ideas ?
Share Improve this question asked Jan 13, 2013 at 23:17 TiuShTiuSh 1452 silver badges9 bronze badges1 Answer
Reset to default 8Use a Response interceptor, and inject your NotificationsService
into it:
angular.module("my.services", [], function ($httpProvider) {
$httpProvider.responseInterceptors.push(function (NotificationsService) {
function notify ( response ) {
angular.forEach(response.notifications, function ( obj ) {
NotificationsService.show( obj );
});
return response;
}
return function ( promise ) {
return promise.then(notify, notify);
}
});
});