AngularJS - $ http和通知服务

Tiu*_*uSh 3 javascript angularjs

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

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

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

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

        ...

    });
Run Code Online (Sandbox Code Playgroud)

当服务器返回嵌入在api中的"notifications"数组时,会触发这个:

{
    notifications: [{type: "error", message: "Error message"}, ...],
    data: [item1, item2, ...]
}
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗 ?

Jos*_*ber 8

使用Response拦截器,并将其注入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);
        }
    });

});
Run Code Online (Sandbox Code Playgroud)