繁体   English   中英

AngularJS - $ http和通知服务

[英]AngularJS - $http and notification service

我正在尝试在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,但我找不到办法这样做!...

有任何想法吗 ?

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

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM