AngularJS ngResource$保存反馈
您好,我正在使用ngResourceAngularJS ngResource$保存反馈,angularjs,ngresource,Angularjs,Ngresource,您好,我正在使用ngResource$save方法,我有两种不同的行为,我不明白为什么 首先,我这样使用它: $scope.user = new User($scope.user); $scope.user.$save(function () { $window.location.href = //redirection here; }, function (response) { $scope.form.addErrors(response
$save
方法,我有两种不同的行为,我不明白为什么
首先,我这样使用它: $scope.user = new User($scope.user);
$scope.user.$save(function () {
$window.location.href = //redirection here;
}, function (response) {
$scope.form.addErrors(response.data.errors);
});
然后,当我执行类似的操作时,我有另一个控制器,但即使从服务器得到404或422个错误,第一次回调被执行,错误回调被忽略
有人知道这件事吗?我已经在谷歌搜索了几个小时,试图找到更多关于$save
的文档,但我仍然遇到这个问题
谢谢。问题出在我用来检测401(未经授权的错误)的拦截器上 这是拦截器,请注意,您必须返回$q.reject(response),否则不会调用其他回调(在我的例子中是ngResource.save中的错误回调)
MyApp.config(函数($httpProvider){
$httpProvider.interceptors.push(函数($window,$q){
返回{
“responseError”:函数(响应){
如果(response.status==401){//unahorized
$window.location.href='index.html';
}
//返回响应;我猜您的$scope.user
对象因位置而异,导致一个调用出错。控制台怎么说它会按预期抛出422错误(因为1字段无效,但仅在后端验证时),但它会执行第一次回调…我正在为不同的模板和不同的表单重用同一个控制器,这可能是原因吗?不应该是问题所在-控制器的每个实例都会创建自己的作用域。错误处理程序可能只会为某些状态代码触发,尝试只返回一个401
?是的,它会重定向我到登录页面,但这仅仅是因为我使用了一个拦截器,我只是对拦截器进行了注释,现在$save方法成功地调用了错误回调,所以问题出在拦截器上。拦截器在这里,我想我必须做些别的事情,而不是仅仅返回响应:myApp.config(function($httpProvider){$httpProvider.interceptors.push(函数($window){return{'responseError':函数(response){if(response.status==401){//Unathorized$window.location.href='index.html';}返回响应;}};};});
MyApp.config(function ($httpProvider) {
$httpProvider.interceptors.push(function($window, $q) {
return {
'responseError': function(response) {
if (response.status == 401) { // Unathorized
$window.location.href = 'index.html';
}
// return response; <-- I was doing this before cancelling all errors
return $q.reject(response);
}
};
});
});