gpt4 book ai didi

javascript - AngularJS:将微调器插入 $httpProvider

转载 作者:行者123 更新时间:2023-12-02 16:11:13 25 4
gpt4 key购买 nike

我在 ng-app 的基本模板中定义了一个微调器。我有以下代码,可以在有事件的 AJAX 请求时自动显示/隐藏它:

app.config(function ($httpProvider) {
// Request interceptor(s)
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
window.httpStart();
return data;
});

// Response interceptor(s)
$httpProvider.responseInterceptors.push('spinnerInterceptor');
})

app.factory('spinnerInterceptor', function ($q, $window) {
return function (promise) {
// Hide spinner on success.
return promise.then(function (response) {
window.httpEnd();
return response;
},

// Hide spinner on failure.
function (response) {
window.httpEnd();
return $q.reject(response);
});
};
});

app.config(function () {
setInterval(function () {
if (typeof (window.httpQueue) != 'undefined') {
if (window.httpQueue > 0) {
angular.element('#ng-loading').show();
} else {
angular.element('#ng-loading').hide();
}
}
}, 50);

/**
* Mark the start of a new HTTP request.
*/
window.httpStart = function httpStart() {
if (typeof (window.httpQueue) == 'undefined') {
window.httpQueue = 0;
};

window.httpQueue++;
};

/**
* Mark the end of a HTTP request.
*/
window.httpEnd = function httpEnd() {
if (typeof (window.httpQueue) != 'undefined') {
window.httpQueue--;
};
};
});

考虑到性能,我讨厌在这里使用 setInterval,特别是因为我们的(公司)用户群将在 IE8 上使用它。

我的担心是没有根据的吗?如果没有,我该如何改进这段代码。

最佳答案

没有理由将帮助器 httpStarthttpEnd 方法放在全局窗口对象上。由于拦截器是使用 .factory() 定义的,因此它可以像任何其他具有自己的函数的 Angular 工厂一样对待,但有一个异常(exception):定义拦截器的推荐方法是返回一个带有 specific properties (response/request/requestError/responseError) 的对象。

拦截器/工厂:

app.factory('spinnerInterceptor', function($q, $rootScope) {
// this gets set once, when the interceptor is first requested.
$rootScope.httpQueue = 0;

return {
'request': function(config) {
$rootScope.httpQueue++;
return config;
},
'response': function(response) {
$rootScope.httpQueue--;
return response;
}
};
});

HTML:

<div id="ng-loading" ng-show="$root.httpQueue > 0"></div>

关于javascript - AngularJS:将微调器插入 $httpProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156578/

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