Search code examples
javascriptangularjshttpbackend

With $httpBackend .then promise works but .success callback doesn't


I have the following backend definition in my test file:

authRequestHandler = $httpBackend.whenPOST(my_request_url)
.respond(
{
    userId: 'panda',
    token: 'panda_token'
});

And in my controller I tried both requests:

$http.post(SignUpUrl)
.success(function (results, status, headers, config) { //this doesn't work
    $scope.data = results.data;
});

And

$http.post(SignUpUrl)
.then(function (results) {   //this works
    $scope.data = results.data;
});

As I noted in the comments, the '.then' promise captures the fake response, while the '.success' callback does not (I get no errors but the debugger doesn't even enter the closure of the callback.

Any ideas why?

Thanks :)


Solution

  • .success spreads the result object up, so the first parameter is the data and not the response object. So the following change should work for your call:

    $http.post(SignUpUrl)
    .success(function (data, status, headers, config) { //this doesn't work
        $scope.data = data;
    });
    

    Also, if you are chaining promises, .success returns the original HttpPromise (result of $http.post) instead of a new promise if you return something in the .success function.