Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting to error page in Angularjs

I am new to AngularJs. I have a single page app with routes configured having a controller and a view. The view get loaded inside the <ng-view></ng-view> element of the index.html page. Inside the controller I am making a http call to get the data and binding the data to the $scope. For success scenarios this works fine but if there is an error how do I plug in another view instead of the default view configured inside the angular route. PLease let me know.

like image 858
zilcuanu Avatar asked Jul 08 '14 07:07

zilcuanu


1 Answers

To implement common scenario for processing ajax errors you can implement custom request interceptor and redirect user to error page (or login page) according to error status:

myApp.factory('httpErrorResponseInterceptor', ['$q', '$location',
  function($q, $location) {
    return {
      response: function(responseData) {
        return responseData;
      },
      responseError: function error(response) {
        switch (response.status) {
          case 401:
            $location.path('/login');
            break;
          case 404:
            $location.path('/404');
            break;
          default:
            $location.path('/error');
        }

        return $q.reject(response);
      }
    };
  }
]);

//Http Intercpetor to check auth failures for xhr requests
myApp.config(['$httpProvider',
  function($httpProvider) {
    $httpProvider.interceptors.push('httpErrorResponseInterceptor');
  }
]);

Plunker here

like image 96
Yuriy Rozhovetskiy Avatar answered Oct 21 '22 08:10

Yuriy Rozhovetskiy