Search code examples
angularjsangularjs-directiveangularjs-scopeangular-ui-router

Angular JS : Post call is going in Success as well as Error Method


I know I amy look like foolish while asking this, but I am not able to figure this out.

I have written a service which handles the post call to the server. $q service is returning the promise back to the controller function which has called the service.

Service :

app.service('AjaxService', ['$http','$q','$log', function($http,$q,$log) {
    return {
        getSearchresultPost : function(url,data){
            var defer = $q.defer();
            $http.post(url, data)
            .then(function(data, status, header, config){
                defer.resolve(data);

            }).then(function(data, status, header, config){
                defer.reject(data);
            });
            return defer.promise;
        }
    };
}]);

Controller

app.controller("kitGuideNavigationController",['$scope','$window','$timeout','AjaxService',function($scope,$window,$timeout,AjaxService){
 AjaxService.getSearchresultPost("/services/knowledge/getProducts",pathToCall)
        .then(function(data){
            console.log("Data ",data);
        }).then(function(data){
            console.log("Some Error Occured");
        });
}]);

When I try to run the code I get both the consoles getting printed.

I am not getting what is getting wrong.Can someone help?


Solution

  • change the second "then" to "catch", should fix this. You have to do this in both cases.

        app.controller("kitGuideNavigationController",['$scope','$window','$timeout','AjaxService',function($scope,$window,$timeout,AjaxService){
     AjaxService.getSearchresultPost("/services/knowledge/getProducts",pathToCall)
            .then(function(data){
                console.log("Data ",data);
            }).catch(function(data){
                console.log("Some Error Occured");
            });
    }]);
    

    update

    also as I saw, you are using the $http, check here