我有一个Angular应用程序,希望从API端点处理404错误。关键组件如下:
// 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
吗?我该如何解决这个问题?
return promise.then(
... 那里,promise
在那里没有定义。http://docs.angularjs.org/api/ng/service/$http - Anthony Chuinceptor
语法的示例? - Darwin Tech