$ resource.query()回调结果意外

时间:2014-01-27 08:14:21

标签: angularjs callback ngresource

我正在开发有角度的网页应用。我想利用查询的错误回调来通知用户刚刚发生了一些错误。但结果不是我的预期,下面是控制器方法:

$scope.fetchAllPlayers = function() {
    $scope.players = PlayerFact.query({
            active: true
        },
        undefined,
        function() {
            console.log('set fetchPlayersFailed to true!!!!');
            $scope.fetchPlayersFailed = true;
        }
    );
};

这是测试代码:

it('fetchAllPlayers: should set fetchPlayersFailed to true when error happens', function() {
    httpBackend.expectGET('/api/players?active=true').respond(500);
    scope.fetchAllPlayers();
    httpBackend.flush();
    expect(scope.fetchPlayersFailed).toEqual(true);
  });

运行单元测试后,这是错误的控制台输出:

Chrome 32.0 (Windows) LOG: 'set fetchPlayersFailed to true!!!!'
Chrome 32.0 (Windows) Controller: PlayerCtrl fetchAllPlayers: should set fetchPl
ayersFailed to true when error happens FAILED
        Expected false to equal true.
        Error: Expected false to equal true.
            at null.<anonymous> (C:/Users/I056958/Documents/My Own/javascript wo
rkspace/redjoker/test/spec/controllers/player.js:111:38)
Chrome 32.0 (Windows) LOG: 'set fetchPlayersFailed to true!!!!'
Chrome 32.0 (Windows): Executed 5 of 5 (1 FAILED) (0.297 secs / 0.043 secs)

注意有2个日志输出:'set fetchPlayersFailed为true !!!!'这意味着错误回调真的被调用而不是一次,两次!!

而且我被告知我所提出的回调不是错误回调,而是成功回调,所以我改变我的代码有点像这样,一切正常:

$scope.fetchAllPlayers = function() {
                $scope.players = PlayerFact.query({
                        active: true
                    },
                    undefined,
                    undefined,
                    function() {
                        console.log('set fetchPlayersFailed to true!!!!');
                        $scope.fetchPlayersFailed = true;
                    }
                );
            };

所以我对回调感到困惑:(以下是引用来自     官方角文件)

HTTP GET "class" actions: Resource.action([parameters], [success], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
non-GET instance actions: instance.$action([parameters], [success], [error])
  1. 根据角色官方文件,查询只是简写 返回对象是数组的GET方法,所以应该只有3个 可选参数:[参数],[成功],[错误],然后为什么 我的第一个版本代码的回调是成功回调,它 应该是错误回调。

  2. 即使我的第一个版本的回调是成功回调,为什么会这样 叫了两次?因为在我的测试代码中,我的回答是500,所以 它根本不应该被调用。

1 个答案:

答案 0 :(得分:0)

在$ httpBackend.flush()之前执行$ rootScope。$ apply(),这应该可行。

暂且不说:$scope.players =没有按照你的想法做到。你需要通过$ resource(...)设置成功回调。获取或通过promise的回调(首选模式)。