javascript - AngularJS - $http 和通知服务

标签 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: [{type: "error", message: "Error message"}, ...],
    data: [item1, item2, ...]
}

现在我想将我的服务连接到 $http,但是我找不到这样做的方法!...

有什么想法吗?

最佳答案

使用 Response interceptor ,并将您的 NotificationsService 注入(inject)其中:

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

});

关于javascript - AngularJS - $http 和通知服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309389/

相关文章:

php - 发送 header 后关闭网页(php)

javascript - 绘制图像函数时出现类型错误

javascript - 当根节点传递给它时,d3 TreeMap 布局是否被缓存?

javascript - 使用AngularJS的OrderBy循环列表进行按索引升序排序的导航

html - 如何使用 Selenium/Protractor 设置 HTML5 类型 ="date"输入字段(例如在 Chrome 中)?

angularjs - 如何测试 AngularJS 指令

javascript - AngularJS + Bootstrap 记住事件选项卡

javascript - 如何在弹出消息框的按钮上设置样式

javascript - 我怎样才能进入完整的 Angular 应用程序状态

AngularJS 与 $resource 和 $httpBackend 的奇怪行为