ng-grid 在使用拦截器修改请求 URL 时不会加载标题行模板$http



我们的应用程序使用$http拦截器向$http请求添加令牌作为一种安全形式,拦截器添加的令牌每5分钟左右更新一次。我们现在想要使用ng-grid

但是,$http拦截器使得ng-grid不会加载它用于头行的模板,这会导致头行无法呈现。

以下是实际问题:http://plnkr.co/edit/krvBF2e4bHauQmHoa05T?p=preview

如果您检查控制台,它会显示以下错误:

GET http://run.plnkr.co/l0BZkZ2qCLnzBRKa/ng1389719736618headerRowTemplate.html?securityToken=123456 404 (Not Found)

之所以会发生这种情况,是因为ng-grid将标题行的模板存储在$templateCache中,然后使用ng-include稍后进行检索

ng-include使用$http.get请求,以$templateCache作为缓存来获取模板。

$http.get请求被拦截器拦截,拦截器在有机会使用url查询$templateCache的模板之前将安全令牌添加到url。

$templateCache期望ng1389719736618headerRowTemplate.html,但却得到ng1389719736618headerRowTemplate.html?securityToken=123456

结果是$templateCache找不到模板,这导致$http.get访问服务器并得到404错误。

另一个问题是,如果我们想使用$templateCache存储模板,然后用ng-include$http.get检索模板,$templateCache将无法找到模板,因为url会被修改。

如何使用$http拦截器将安全令牌添加到URL的末尾,使ng-grid显示标题行?

这是代码Html:

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>  
<link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body ng-controller="MyCtrl">
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
</html>

javascript:

var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.myData = [{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34}];
$scope.gridOptions = { data: 'myData' };
});
app.config(function($provide, $httpProvider) {
$provide.factory('tokenAuthInterceptor', function($q){
return {
// optional method
'request': function(config) {
// do something on success
config.url = config.url + "?securityToken=123456";
return config || $q.when(config);
}
};
});
$httpProvider.interceptors.push('tokenAuthInterceptor');
});

更新

最终决定的解决方案是使用角度装饰器并装饰$templateCache,plunker被更新以反映这一点。

$provide.decorator('$templateCache', function($delegate) {
var get = $delegate.get;
function formatKey(key)
{
// code for formatting keys
}
$delegate.get = function(key) {
var entry = get(key);
if (entry)
{
return entry;
}
else
{
return get(formatKey(key));
}
};
return $delegate;
});

我们遇到了同样的问题,并在拦截器中实现了一个快速检查,以检查该项是否已经在templateCache中。

if ($templateCache.get(config.url)){
return config;
}

这个主意是我从"破纪录者"项目中得到的。

最新更新