mikelplhts
mikelplhts

Reputation: 1211

Redirect to a 404 after a GET error

Is it possible to redirect, without changing the URL, in a specific controller? I would like that, if into a controller I have an error from a GET request, it must show me the 404 page. For instance, I have the following files.

index.html:

<!DOCTYPE html>
<html ng-app="app" ng-controller="MainCtrl">
<head>
    ...
</head>
<body>
    ...
    <ng-view></ng-view>
    ...
</body>
</html>

app.js:

angular
.module('app', [...])
...
.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'views/home.html',
        controller:  'HomeCtrl'
    })
    .when('/page1', {
        templateUrl: 'views/page1.html',
        controller:  'Page1Ctrl'
    })
    .when('/page2', {
        templateUrl: 'views/page1.html',
        controller:  'Page2Ctrl'
    })
    .when('/page3', {
        templateUrl: 'views/page3.html',
        controller:  'Page1Ctrl'
    })
    ...
    .otherwise({
        templateUrl: 'views/404.html',
        controller:  '404Ctrl'
    });
});

The redirect, for example, must be make in page1.js

angular.module('app')
.controller('Page1Ctrl', function($scope, $http) {
    $http.get(...).then(function() {
        // all ok.
    }, function() {
        // error, redirect to 404 page.
    });
});

How I can do that?

Upvotes: 0

Views: 675

Answers (1)

Kiran Pawar
Kiran Pawar

Reputation: 322

Your route for 404 page should be :

.when('/404Page', {
    templateUrl: 'views/404.html',
    controller:  '404Ctrl'
});

And You can handle it in interceptor as follows :

$provide.factory('MyHttpInterceptor', function ($q, $window ) {
    return {

        // On response failture
        responseError: function (rejection) {

          if(rejection.status==400)
             $state.go('404Page');

          return $q.reject(rejection);
        }
    }
  });
  //push interceptor into interceptors array
  $httpProvider.interceptors.push('MyHttpInterceptor');

I hope this would help you.

Upvotes: 2

Related Questions