【问题标题】:Angular: $http 404 error handlingAngular:$http 404 错误处理
【发布时间】:2012-11-16 04:28:26
【问题描述】:

我有一个包含 2 个 ng-includes 的 HTML。考虑服务器中是否不存在 ng-include src 之一。到目前为止,它只会加载空白 html,并且在浏览器控制台中会说找不到 http-404 文件。

因此,在这种情况下,我只想将默认错误页面(存在于服务器中)加载到该特定 div 中,即一半显示默认错误页面,另一半显示通过 nginclude 加载的正确 div。

我的逻辑是,我正在使用一个 http 拦截器,在那里我拦截所有 http 调用。每当 404 发生时,我想返回必须仅加载到 div 中的默认错误页面。所以它就像模拟一个正确的 http 调用,但发送一个错误页面,我假设它必须加载到正确的 div。

但这并没有发生 :)。我尝试使用默认的 window.load('')。但随后它会加载到页面顶部并跨页面呈现。

或者我应该捕获 div id(如果是怎么做?)然后执行 tat id 加载默认错误 HTML?

需要你的想法。

【问题讨论】:

  • 你有你想要做什么的例子吗?也许是一把小提琴

标签: javascript jquery html angularjs


【解决方案1】:

要处理这种情况,您可以使用 http 拦截器(在此处查找文档:$http)。

拦截器必须捕获 404 响应,从您的服务器加载 404.html 页面并 将其设置为初始响应的 data 以及 status 代码 200。

我创建了一个项目来展示如何解决它。

存储库:https://github.com/matys84pl/angularjs-nginclude-handling-404/

仔细查看main.js 文件。

【讨论】:

    【解决方案2】:

    我做了类似的事情,在填充 ng-include 值之前直接通过 $http 传递所需的 ng-include url。

    $http({ url: url, method: "GET", cache: $templateCache}).success(function(data) {
            /* there was a template for this url - set the $scope property that 
             * the ng-include is using
             */
            $scope.templateUrl = url;
        }).error(function () {
            // there was not a template for this url - set the default one
            $scope.templateUrl = defaultUrl;
        });
    

    这里的技巧是将 $templateCache 作为缓存参数传递给 $http - 这意味着获取的 url 存储在 ng-include 使用的同一个缓存中,因此当您找到一个有效的模板并将其设置在templateUrl 属性,ng-include 不需要再次获取模板。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2016-07-12
      • 2017-12-16
      • 2019-12-19
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多