gpt4 book ai didi

javascript - AngularJS - $http 和通知服务

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:26:06 24 4
gpt4 key购买 nike

我正在尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com