我正在尝试在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,但我找不到办法这样做!...
有什么想法吗?
答案 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);
}
});
});