我们正在使用 AngularJS 和 ASP.NET MVC Json Rest API 开发单页应用程序。
当未经身份验证的客户端尝试导航到私有(private)路由(例如:/Foo/Home/Template)以获取模板时,它会自动从 Web API 和我们的 AngularJS 应用程序获得 401 响应将其重定向到登录页面。
我们正在用 $http interceptor 处理 401像这样:
if (response.status === 401) {
$location.path(routeToLogin);
return $q.reject(response);
}
输入正确的凭据允许客户端获取模板。
除一个细节外,一切正常; Javascript 控制台报告此错误:
Error: [$compile:tpload] http://errors.angularjs.org/1.3.0/$compile/tpload?p0=%Foo%2FHome%2FTemplate%2F
Description
This error occurs when $compile attempts to fetch a template from some URL, and the request fails.
在我们的 AngularJs 应用程序中,请求失败但这是设计使然,因为资源在那里但无法访问 (401)。
我应该继续并在控制台上接受这种错误,还是可以通过某种方式将其静音或屏蔽?
编辑:
我对 Angular 源进行了一些调试,我发现了代码的哪一部分引发了异常。
由于我们使用 TemplateUrl
来声明我们的模板,因此我们间接使用了进行此调用的函数 compileTemplateUrl
:
$templateRequest($sce.getTrustedResourceUrl(templateUrl))
这使得 templateRequest
的第二个参数 (ignoreRequestError
) 未定义。
ignoreRequestError(optional)boolean
Whether or not to ignore the exception when the request fails or the template is empty
当我们的 http 拦截器在处理 401 状态代码时拒绝 promise ,$TemplateRequestProvider
中的 $http.get 将失败并调用此函数:
function handleError() {
self.totalPendingRequests--;
if (!ignoreRequestError) {
throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
}
return $q.reject();
}
我相信我们无法采取任何措施来防止控制台上的错误,因为 TemplateUrl
不允许将 ignoreRequestError
标志设置为 false。
我试图在 401 状态代码的情况下绕过拒绝;这修复了控制台上的错误,但遗憾的是它有副作用:一个空模板被错误地缓存到 TemplateCache
中导致其他问题。
最佳答案
想了想想起了Angular中的decorating,完美解决了这个问题:
app.config(['$provide', function($provide) {
$provide.decorator('$templateRequest', ['$delegate', function($delegate) {
var fn = $delegate;
$delegate = function(tpl) {
for (var key in fn) {
$delegate[key] = fn[key];
}
return fn.apply(this, [tpl, true]);
};
return $delegate;
}]);
}]);
关于javascript - 如何避免 $compile :tpload errors on 401 status code response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26811211/