AngularJS - $ http和通知服务

时间:2013-01-13 23:17:59

标签: javascript angularjs

我正在尝试在angularJS上构建一个简单的通知服务:

angular.module("my.services", [])
    .service("NotificationsService", function() {

        this.show  = function(message, options) {
            // display a notification
        };

        this.error = function(message) {
            this.show({...});
        }

        ...

    });

当服务器返回api中嵌入的“notifications”数组时会触发:

{
    notifications: [{type: "error", message: "Error message"}, ...],
    data: [item1, item2, ...]
}

现在我想将我的服务插入$ http,但我找不到办法这样做!...

有什么想法吗?

1 个答案:

答案 0 :(得分:8)

使用Response interceptor,然后将NotificationsService注入其中:

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

});