AngularJS使用拦截器来处理$ http 404s - 承诺未定义错误

时间:2014-02-20 20:14:57

标签: angularjs angular-http

我有一个Angular应用程序,我想为404处理API端点。关键部分是这样的:

// app.js

var myApp = angular.module('myApp', ['ngRoute',]);

myApp.config( function ($httpProvider, $interpolateProvider, $routeProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');

  $routeProvider
    ...
    .when('/project/:projectId', {
        templateUrl : 'partials/project_detail.tmpl.html',
        controller: 'ProjectDetailCtrl',
        resolve: {
            project: function ($route, ConcernService) {
                return ConcernService.get('projects/', $route.current.params.projectId);
            },
        }
    });
});


// interceptors.js

myApp.factory('httpRequestInterceptor', function ($q, $location) {
  return {
    response: function(response){
      return promise.then(
        function success(response) {
          return response;
        },
        function error(response) {
          if(response.status === 404){
            $location.path('/404');
            return $q.reject(response);
          }
          else{
            return $q.reject(response); 
          }
        }
      );
    }
  };
});


// services.js

myApp.factory('ConcernService', function ($http, $q) {

var ConcernService = {
    ...
    get: function (items_url, objId) {
        var defer = $q.defer();
        $http({method: 'GET', 
            url: api_url + items_url + objId}).
            success(function (data, status, headers, config) {
                defer.resolve(data);
            }).error(function (data, status, headers, config) {
                // when API not found, status == 404 
                console.log('ConcernService.get status',status);
                defer.reject(status);
            });
        console.log('ConcernService.get promise',defer.promise);
        return defer.promise;
    },
}
});

问题是我收到ReferenceError: promise is not defined at response错误。这是因为ConcernService推迟了promise吗?我该怎么处理这个?

3 个答案:

答案 0 :(得分:34)

因此,我使用新interceptor语法的解决方案如下:

// 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>

这是一个简化版本,但演示了我如何使用interceptor模式来解决我的问题。

欢迎提出意见。

答案 1 :(得分:2)

我认为拦截器的结构可能已关闭。我在这里发布了一个样本拦截器(Handle HTTP 302 response from proxy in angularjs)的答案,你可能会发现它很有用。它每天都适合我。

答案 2 :(得分:0)

更容易将参数传递为

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

然后当项目ID不存在时

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