LJ Wadowski
LJ Wadowski

Reputation: 6720

Handle AngularJS errors while loading template file

I create an app with requirement of template files being in two folders - first is available without restrictions and second is available only for logged in users.

Things are complicating when somebody refresh the page and session expire before. Angular throws error (e.g. 401) in console while loading template file which I want to avoid. Is there a way to catch that event and access response status to for e.g. redirect the page?

Upvotes: 0

Views: 54

Answers (1)

Arun AK
Arun AK

Reputation: 4370

For your case, we can catch the error and redirect to a page with the help of $location.url(). Here is the concept. Now i have a controller and in that, i have success function and error function. Whenever we get an error, the error function will run and we can pass the link of the page you want to redirect.

$http.get(url,[params])
     .success(function(data, status, headers, config){
    // bind your data to scope
      })
     .error(function(data, status, headers, config) {
        $location.url('/404');
      });

By the use of $routeProvider, you can configure the function something like this :

$routeProvider
   .when('/404', {
       templateUrl: '404.html',
       controller: 'yourcontroller'
});

And you can see the description for $location.url() here

Hope it works

Upvotes: 1

Related Questions