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

…衆ロ難τιáo~ 提交于 2019-12-02 20:38:52
Darwin Tech

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

...

<h1>Oh No! 404.</h1> 
<p>Project with ID {{ project.id }} does not exist.</p>

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

Comments are welcome.

MBielski

I think the structure of you interceptor might be off. I posted an answer with a sample interceptor here (Handle HTTP 302 response from proxy in angularjs) that you might find useful. It works for me on a daily basis.

Is just easier to pass parameter as

<div class="fullPortfolio" ng-show="projectId.length">Project Id passed</div>

and then when project id is not exist

<div class="fullPortfolio" ng-show="!projectId.length">Project Id is not exist</div>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!