Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage 404 errors loading directive templates in AngularJS

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?

like image 379
francadaval Avatar asked Jun 23 '15 10:06

francadaval


2 Answers

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

like image 178
dfsq Avatar answered Sep 17 '22 23:09

dfsq


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!

like image 34
nalinc Avatar answered Sep 18 '22 23:09

nalinc