How to manage 404 errors loading directive templates in AngularJS

In the AngularJS directive, the templateUrl parameter is defined dynamically.

 'templates/' + content_id + '.html' 

I do not want to establish rules for checking the validity of the content_id value and managing it as 404 errors, i.e. if the template does not exist (the server returns a 404 error when loading the template) load template/404.html instead.

How can i do this?

Edited: Current answers suggest using a response error interceptor. In this case, ¿How can I know what the response to downloading this template is?

+6
source share
2 answers

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

 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

+6
source

You can create an interceptor to track all requests made by the $http service and catch any response errors. If you get 404 status for any request made, just redirect the user to the 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 will need to push the interceptor on $httpProvider in your configuration.

 myApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) { $httpProvider.interceptors.push('httpRequestInterceptor'); }); 

Here is a demo

Hooray!

+4
source

Source: https://habr.com/ru/post/989601/


All Articles