igo*_*igo 15 javascript interceptor angularjs
我有一个Angular拦截器工作:
factory('myHttpInterceptor', function ($q, $location, $rootScope) {
// do something
return function (promise) {
return promise.then(function (response) {
// do something
return response;
}, function (response) {
// do something
return $q.reject(response);
});
};
})
Run Code Online (Sandbox Code Playgroud)
和一个包含模板的大html文件<script type="text/ng-template" id="home-template">.不幸的是,我的HTTP拦截器不仅拦截加载HTTP请求,还拦截加载模板(已经加载到html文件中),用于定义为的控制器when('/', {controller:MainController, templateUrl:'home-template'}).有没有办法如何使拦截器只拦截HTTP请求或如何识别我是从服务器加载某些东西还是只是模板?
Kev*_*n M 23
我也遇到了这个问题.我们使用拦截器向所有$ http调用添加查询字符串.它最终打破了我们的模板,因为在查看$ templateCache时,找不到带有查询字符串的模板名称(模板最初是使用它的id缓存的).
Angular $ httpProvider拦截器将拦截$ http模块调用.这些$ http调用不一定是真正的HTTP GET/POST请求,它们也可以调用来获取$ templateCache中的模板.似乎在引用嵌入式模板时,首先使用$ http模块(首先运行拦截器),然后$ http模块将查看$ templateCache以查看模板是否已被缓存.如果$ http发现$ templateCache中存在该项,则它将返回它,否则它将尝试发出实际的HTTP请求来获取模板.
我们的解决方案是在拦截器中包含$ templateCache模块,并首先手动检查$ templateCache中是否存在http请求.如果请求不在$ templateCache中,请添加我们的查询字符串,如果它在$ templateCache中,则只需返回它.
$httpProvider.interceptors.push(function($templateCache) {
return {
'request' : function(request) {
// If the request is a get and the request url is not in $templateCache
if(request.method === 'GET' && $templateCache.get(request.url) === undefined) {
// Item is not in $templateCache so add our query string
request.url = request.url + '?time=' + new Date().getTime();
}
return request;
}
};
});
Run Code Online (Sandbox Code Playgroud)
根据我收集的信息,您正在寻找一种方法来查看请求是否涉及模板文件。您可以做的是查看url请求的 并查看它是否包含部分目录的路径。
让我知道这是否是您正在寻找的:
var interceptor = ['$location', '$log', '$q', function($location, $log, $q) {
function success(response) {
// you can examine the url of the request here
$log.info(response.config.url)
return response;
}
function error(response) {
if (response.status === 401) {
$location.path('/signin');
return $q.reject(response);
} else {
return $q.reject(response);
}
}
return function(promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5157 次 |
| 最近记录: |