angularjs作为一个全ajax的框架,对于请求,如果页面上不做任何操作的话,在结果烦回来之前,页面是没有任何响应的,不像普通的HTTP请求,会有进度条之类。
什么是拦截器?
$httpProvider 中有一个 interceptors 数组,而所谓拦截器只是一个简单的注册到了该数组中的常规服务工厂。下面的例子告诉你怎么创建一个拦截器:
rush:js;">
module.factory('myInterceptor',['$log',function($log) {
$log.debug('$log is here to show you that this is a regular factory with injection');
var myInterceptor = {
....
....
....
};
return myInterceptor;
}]);
然后通过它的名字添加到 $httpProvider.interceptors 数组:
rush:js;">
module.con
fig(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);
先给大家展示下效果图:
本文通过对httpProvider注入拦截器实现loading。
rush:js;">
app.con
fig(["$routeProvider","$httpProvider",function ($routeProvider,$httpProvider) {
$routeProvider.when('/',{
templateUrl: "/views/reminder/index.html",controller: "IndexController"
});
$routeProvider.when('/create',{
templateUrl: "/views/reminder/item/create.html",controller: "ItemCreateController"
});
$routeProvider.otherwise({redirectTo: '/'});
$httpProvider.interceptors.push('timestampMarker');
}]);
//loading
app.factory('timestampMarker',["$rootS
cope",function ($rootS
cope) {
var timestampMarker = {
request: function (con
fig) {
$rootS
cope.loading = true;
con
fig.requestTimestamp = new Date().getTime();
return con
fig;
},response: function (response) {
// $rootS
cope.loading = false;
response.con
fig.responseTimestamp = new Date().getTime();
return response;
}
};
return timestampMarker;
}]);