使用angular $ resource,我想在请求成功发送到restful后端时触发回调函数。 (后端可能需要很长时间,我只想知道它是否收到了我发送的数据。)
到目前为止我唯一发现的是resource.action.$promise['finally'](callback);
我也有兴趣知道何时无法发送请求。 (例如,连接问题)
谢谢!
答案 0 :(得分:1)
这是DRY方法:
构建拦截每个HTTP请求(like the one defined in the official documentation)的服务:
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
只需将代码放在所需的钩子中即可。例如,如果请求失败,您可以绘制错误模式对话框。
最后,将其注册到您的应用程序:
app.config(['$httpProvider', function($httpProvider) {
// Add the interceptor to the $httpProvider to intercept http calls
$httpProvider.interceptors.push('myHttpInterceptor');
}]);