3

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 ?

1 Answer 1

8

Use 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);
        }
    });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.