AngularJS-处理$http错误?
我有一个指令,我正在向其中注入一个服务,该指令对后端服务进行AngularJS-处理$http错误?,angularjs,Angularjs,我有一个指令,我正在向其中注入一个服务,该指令对后端服务进行$http调用 您通常如何处理404/401/HTTP错误?我正在寻找最佳实践模式 当承诺遇到http错误时,$http是否会吞并并拒绝承诺 到目前为止,这就是我所拥有的,它似乎工作正常,但我不确定我是否按照建议的方式工作: 服务 app.service('helpService', ['$http', function ($http) { return { getHelpUrl: function (pageU
$http
调用
您通常如何处理404/401/HTTP错误?我正在寻找最佳实践模式
当承诺遇到http错误时,$http
是否会吞并并拒绝承诺
到目前为止,这就是我所拥有的,它似乎工作正常,但我不确定我是否按照建议的方式工作:
服务
app.service('helpService', ['$http', function ($http) {
return {
getHelpUrl: function (pageUrl) {
return $http.post('Home/GetHelpUrl', { pageUrl: pageUrl });
}
}
}]);
app.directive('helpLink', ['$location', 'helpService', function ($location, helpService) {
return {
restrict: 'A',
replace: true,
scope: {},
template: function (elem, attrs) {
return '<a ng-href="{{helpUrl}}" ng-show="showLink" target="_blank">Help?</a>';
},
link: function (scope, elem, attrs) {
scope.showLink = false;
helpService.getHelpUrl($location.path()).success(function (data) {
scope.helpUrl = data.helpUrl;
scope.showLink = true;
});
}
}
}]);
指令
app.service('helpService', ['$http', function ($http) {
return {
getHelpUrl: function (pageUrl) {
return $http.post('Home/GetHelpUrl', { pageUrl: pageUrl });
}
}
}]);
app.directive('helpLink', ['$location', 'helpService', function ($location, helpService) {
return {
restrict: 'A',
replace: true,
scope: {},
template: function (elem, attrs) {
return '<a ng-href="{{helpUrl}}" ng-show="showLink" target="_blank">Help?</a>';
},
link: function (scope, elem, attrs) {
scope.showLink = false;
helpService.getHelpUrl($location.path()).success(function (data) {
scope.helpUrl = data.helpUrl;
scope.showLink = true;
});
}
}
}]);
app.directive('helpLink',['$location','helpService',function($location,helpService){
返回{
限制:“A”,
替换:正确,
作用域:{},
模板:函数(元素、属性){
返回“”;
},
链接:功能(范围、要素、属性){
scope.showLink=false;
helpService.getHelpUrl($location.path()).success(函数(数据){
scope.helpUrl=data.helpUrl;
scope.showLink=true;
});
}
}
}]);
如果您想捕获所有错误,您可能会在拦截器中查找。看一看这张照片。您还可以在方法中使用错误回调。(这将取代您的.success
方法),因为$http
返回承诺(请参见$q):
拦截器可以注册如下内容:
app.config(function($httpProvider){
$httpProvider.interceptors.push('connectionInterceptor');
});
app.factory('connectionInterceptor', function ($q) {
return {
'requestError':function(rejection){
//do something general (global)
//send a rejection
},
'responseError': function (response) {
//do something general (global)
//send a rejection
}
};
});
与success
方法一样,还有一个错误(函数(数据、状态、标题、配置)
方法是通过$http定义的
这是文档中的示例
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
您可以使用它捕获中的错误。然后您是这样说的:.then(function(successResult){},function(errorResult){};
?是的,请参阅successResult
和errorResult
的对象结构的“方法”右上方的“返回”部分