In an AngularJS directive the templateUrl
parameter is defined dinamically.
'templates/' + content_id + '.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.
How can I do that?
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');
});
Demo: http://plnkr.co/edit/uCpnT5n0PkWO53PVQmvR?p=preview
You can create an interceptor
to monitor all requests made with the $http
service and intercept any response errors. If you get a status 404 for any request made, simply redirect the user to error page(template/404.html
in your case).
.factory('httpRequestInterceptor', function ($q) {
return {
'responseError': function(rejection) {
if(rejection.status === 404){
// do something on error
}
}
return $q.reject(rejection);
}
};
});
You would need to push the interceptor to $httpProvider
in your config function.
myApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
Here's the demo
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With