[英]How to manage 404 errors loading directive templates in AngularJS
在AngularJS指令中, templateUrl
參數是動態定義的。
'templates/' + content_id + '.html'
我不想建立規則來檢查content_id
值是否有效並將其管理為404錯誤,即,如果模板不存在(服務器在加載模板時返回404錯誤),請改為加載template/404.html
。
我怎樣才能做到這一點?
編輯:當前答案建議使用響應錯誤攔截器。 在這種情況下,我怎么知道響應是對此模板的加載?
您將需要編寫響應錯誤攔截器。 像這樣:
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');
});
您可以創建一個interceptor
來監視使用$http
服務發出的所有請求並攔截任何響應錯誤。 如果您針對任何請求獲得狀態404,只需將用戶重定向到錯誤頁面(在您的情況下為template/404.html
)。
.factory('httpRequestInterceptor', function ($q) {
return {
'responseError': function(rejection) {
if(rejection.status === 404){
// do something on error
}
}
return $q.reject(rejection);
}
};
});
您需要在配置函數中將攔截器推送到$httpProvider
。
myApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
這是演示
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.