最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS - $http and notification service - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 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);
        }
    });

});
发布评论

评论列表(0)

  1. 暂无评论