Skip to content Skip to sidebar Skip to footer

Angularjs - Unable To Call Http Serrvice Using Factory

To resolve my issue I have gone through many articles on different sites, but none resolved it. I'm writing a simple AngularJS application. I'm quite new to Angular. I have written

Solution 1:

Try something like this instead:

var app = angular.module("app", [])
            .controller("controller", function ($scope, WebFactory) {
                $scope.data = "data";
                $scope.error = "error";
                $scope.data = {}
                WebFactory.getData().then(functionsuccess(response) {
                        $scope.data = response.data;
                    });
            })
            .factory("WebFactory", function ($http) {
                var obj = {};

                obj.getData = function()
                {
                    return$http({
                        method: "GET",
                        url: "http://localhost:37103/api/employee",                      
                    })
                }
                return obj;
            });

Solution 2:

First of all, you're missing an ng-app declaration

Secondly, you are misusing the then callback. It accepts three parameters: success callback, error callback, finally callback. As the first then executes the success, then it executes the second callback that always returns the response, but I assume it is not intended to be that way and you could use the get function which is more easy to use. It should be:

$http.get("http://localhost:37103/api/employee").then(function(response){
     //Do something with successfull response
 },
  function(error){ //do something with the error});

See documentation about promises

Lastly, you are dealing with promises and async code, yet returning response or string instead of the promise with the result. So the getData() should look like this:

obj.getData = function(){
   return$http.get("http://localhost:37103/api/employee");
}

And use the then(success,error,finally) callbacks in the controller or if you want to provide values on the error/finally callbacks in the service, you should use the $q service

obj.getData(){
 var deferred = $q.defer();
 $http.get(...).then(function(response){
      deferred.resolve(response.data);
   },
   function(error){
       deferred.reject("No Data");
   });
  return deferred.promise;
}

Of course you would have to provide $q service to the WebFactory

Post a Comment for "Angularjs - Unable To Call Http Serrvice Using Factory"