javascript - 如何避免 $compile :tpload errors on 401 status code response

标签 javascript angularjs single-page-application angularjs-routing

我们正在使用 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

AngularJs documentation声明如下:

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/

相关文章:

javascript - 阻止自动对焦在跨域子帧中的 <input> 元素上

php - 如何为谷歌地图创建可拖动的自定义标记列表

javascript - 缺少形式参数

authentication - 是否可以在不重定向到外部登录页面的情况下进行SPA身份验证

javascript - 从基于 JavaScript 的网页中提取表格

javascript - 从服务器加载 html 和 Controller 并创建动态状态 UI - 路由器

angularjs - uib-工具提示 : conditionally show or hide tooltip

javascript - 在 Angular gridOptions 中调用另一个函数

angular - 如何在 VS2017 SPA 模板中使用 Angular Material

angular - AMP(加速移动页面)是否与 angular2 兼容?