【问题标题】:AngularJS ngResource $save feedbackAngularJS ngResource $save 反馈
【发布时间】:2014-05-19 23:18:10
【问题描述】:

您好,我正在使用 ngResource $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 错误,第一个回调也会被执行,错误回调会被忽略。

有人知道吗?我在 Google 中搜索了几个小时,试图找到更多关于 $save 的文档,但我仍然遇到这个问题。

谢谢。

【问题讨论】:

  • 我猜测您的 $scope.user 对象因位置而异,导致一次调用出错。控制台说什么
  • 它按预期抛出 422 错误(因为 1 字段无效,但仅在后端验证时),但随后它执行第一个回调......我正在为不同的模板和不同的表单重用相同的控制器,会是这个原因吗?
  • 不应该是问题 - 控制器的每个实例都会创建它自己的范围。错误处理程序可能只针对某些状态代码触发,请尝试仅返回 401?
  • 是的,它会将我重定向到登录页面,但只是因为我使用了拦截器,我只是评论了拦截器,现在 $save 方法成功调用了错误回调,所以问题出在拦截器。
  • 这里是拦截器,我想我必须做点别的,而不是仅仅返回响应: myApp.config(function ($httpProvider) { $httpProvider.interceptors.push(function($window) { return { 'responseError': function(response) { if (response.status == 401) { // Unathorized $window.location.href = 'index.html'; } return response; } }; }); }) ;

标签: angularjs ngresource


【解决方案1】:

嗯,问题出在我用来检测 401(未经授权的错误)的拦截器上

这里是拦截器,注意你必须返回 $q.reject(response) 否则不会调用其他回调(在我的例子中是 ngResource.$save 中的错误回调)

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);
            }
        };
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2015-01-09
    • 2015-10-27
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多