I'm developing angular web app. I want to utilize the error callback of query to inform user that there's some error just happened. But the Result is just not what I expected, below is the controller method:
$scope.fetchAllPlayers = function() {
$scope.players = PlayerFact.query({
active: true
},
undefined,
function() {
console.log('set fetchPlayersFailed to true!!!!');
$scope.fetchPlayersFailed = true;
}
);
};
And here's the test code:
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);
});
After I run unit tests, here's the console output of the error:
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)
Notice that there're 2 log outputs: 'set fetchPlayersFailed to true!!!!' That means the error callback really gets called and not once, twice!!
And I'm told that the callback I put is not error callback, instead it's the success callback, So I alter my code a bit like this, everything works just fine:
$scope.fetchAllPlayers = function() {
$scope.players = PlayerFact.query({
active: true
},
undefined,
undefined,
function() {
console.log('set fetchPlayersFailed to true!!!!');
$scope.fetchPlayersFailed = true;
}
);
};
So I'm confused about the callbacks:(below is the quote from official angular document)
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])
According to angular official document, query is just shorthand for GET method whose return object is array, so there should be only 3 optional paramters: [parameters], [success], [error], then why is the callback of my first version code is the success callback, it should be exactly the error call back.
Even if my first version's callback is success callback, why will be called twice?? Because in my test code, I did respond with 500, so it shouldn't get called at all.