在更新/创建一些数据后,我们需要向用户显示错误/成功消息,这可能是一种常见情况,我们如何在AngularJS中实现它?
我想添加回调但无法找到解决方案。使用$ http.post()。success()。error()可以工作,但我想知道我是否可以用更高的杠杆API $资源来实现。
或者,我们应该写指令或使用$ watch()?
感谢您的帮助。
答案 0 :(得分:51)
来自资源类的操作可以传递成功和错误回调,就像较低级 $ http 服务一样
非获取操作的前缀为$
。
所以你可以这样做
User.get({userId:123}, function(u, getResponseHeaders){
// this is get's success callback
u.abc = true;
u.$save(function(u, putResponseHeaders) {
// This is $save's success callback, invoke notification from here
});
});
编辑:这是another example from a previous plunker。 get请求将失败,因为它请求不存在的json文件。将运行错误回调。
someResource.get(function(data){
console.log('success, got data: ', data);
}, function(err){
alert('request failed');
});
答案 1 :(得分:5)
使用最新的AngularJS版本,您可以查看属于$httpProvider
的{{3}}。
然后,您可以在发送之前或响应之后拦截所有请求。
angular.module('app').config(function($httpProvider){
$httpProvider.interceptors.push(function($q) {
return {
'request': function(config) {
console.log('I will send a request to the server');
return config;
},
'response': function(response) {
// called if HTTP CODE = 2xx
console.log('I got a sucessfull response from server');
return response;
}
'responseError': function(rejection) {
// called if HTTP CODE != 2xx
console.log('I got an error from server');
return $q.reject(rejection);
}
};
});
});
请注意,您必须返回config
或response
才能使其正常运行。
对于rejection
,您需要返回延迟拒绝,以便在拦截后让$http.get().error()
仍然有效。