【发布时间】:2014-02-17 23:51:15
【问题描述】:
我正在开发 Angular Web 应用程序。我想利用查询的错误回调来通知用户刚刚发生了一些错误。但是结果不是我所期望的,下面是控制器方法:
$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])
根据角度官方文档,查询只是简写 返回对象为数组的GET方法,所以应该只有3个 可选参数:[参数],[成功],[错误],那为什么是 我的第一个版本代码的回调是成功回调,它 应该正是错误回调。
即使我的第一个版本的回调是成功回调,为什么会是 叫了两次??因为在我的测试代码中,我确实回复了 500,所以 它根本不应该被调用。
【问题讨论】:
标签: angularjs callback ngresource