我正在开发有角度的网络应用程序。我想利用查询的错误回调来通知用户刚刚发生了一些错误。但是结果并不是我所期望的,下面是控制器方法:
$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])
根据angular官方文档,query只是返回对象为数组的GET方法的简写,所以应该只有3个可选参数:[parameters]、[success]、[error],那为什么我的第一个版本代码的回调是成功回调,应该就是错误回调。
即使我的第一个版本的回调是成功回调,为什么会被调用两次?因为在我的测试代码中,我确实响应了 500,所以根本不应该调用它。