AngularJS using an interceptor to handle $http 404s - promise not defined error

前端 未结 3 880
庸人自扰
庸人自扰 2021-02-01 20:01

I have an Angular app, for which I want to handle 404s form an API end point. The key components are like so:

// app.js

var myApp = angular.module(\'myApp\', [\         


        
3条回答
  •  迷失自我
    2021-02-01 20:40

    So, my solution which works, using the new interceptor syntax is as follows:

    // interceptors.js
    
    .factory('httpRequestInterceptor', function ($q, $location) {
        return {
            'responseError': function(rejection) {
                // do something on error
                if(rejection.status === 404){
                    $location.path('/404/');                    
                }
                return $q.reject(rejection);
             }
         };
    });
    
    
    // app.js
    
    myApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) {
        $httpProvider.interceptors.push('httpRequestInterceptor');
    
        $routeProvider
        ...
        .when('/404/:projectId', {
            templateUrl : 'partials/404.tmpl.html',
            controller: '404Ctrl',
            resolve: {
                project: function ($route) {
                    // return a dummy project, with only id populated
                    return {id: $route.current.params.projectId};
                }
            }
        });
    });
    
    
    // 404.tmpl.html
    
    ...
    
    

    Oh No! 404.

    Project with ID {{ project.id }} does not exist.

    This is a simplified version, but demonstrates how I used the interceptor pattern to solve my issue.

    Comments are welcome.

提交回复
热议问题