0

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

$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 to 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. 根据angular官方文档,query只是返回对象为数组的GET方法的简写,所以应该只有3个可选参数:[parameters]、[success]、[error],那为什么我的第一个版本代码的回调是成功回调,应该就是错误回调。

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

4

1 回答 1

0

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

顺便说一句:$scope.players =不做你认为它做的事。您需要通过 $resource(...).get 或通过来自 promise 的 then 回调(首选模式)在成功回调中设置它。

于 2014-01-28T03:23:27.580 回答