如何管理404错误在AngularJS加载指令模板 [英] How to manage 404 errors loading directive templates in AngularJS

查看:600
本文介绍了如何管理404错误在AngularJS加载指令模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个AngularJS指令中的 templateUrl 参数dinamically定义。

In an AngularJS directive the templateUrl parameter is defined dinamically.

'templates/' + content_id + '.html'

我不希望建立的规则,以检查是否 CONTENT_ID 值是有效的,它管理为404错误,也就是说,如果模板不存在(服务器回报404错误加载模板)负载时模板/ 404.html 代替。

I don't want to establish rules to check if content_id value is valid and manage it as 404 errors, i.e. if the template doesn't exist (server return a 404 error when loading the template) load template/404.html instead.

我怎么能这样做?

编辑:当前的答案建议使用响应错误拦截。在这种情况下¿我怎么能知道反应是这个模板的加载?

Edited: The current answers suggest to use a response error interceptor. In this case ¿how can I know that the response is to a loading of this template?

推荐答案

您需要编写响应误差拦截器。事情是这样的:

You will need to write response error interceptor. Something like this:

app.factory('template404Interceptor', function($injector) {
    return {
        responseError: function(response) {
            if (response.status === 404 && /\.html$/.test(response.config.url)) {
                response.config.url = '404.html';
                return $injector.get('$http')(response.config);
            }
            return $q.reject(response);
        }
    };
});

app.config(function($httpProvider) {
    $httpProvider.interceptors.push('template404Interceptor');
});

演示: http://plnkr.co/edit/uCpnT5n0PkWO53PVQmvR?p=$p$pview

这篇关于如何管理404错误在AngularJS加载指令模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆