Rakesh Burbure Rakesh Burbure - 1 month ago 13
AngularJS Question

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 a factory method which call the $http service which gets the data from the web api. Web api is running fine and its returning the JSON object as expected.

Angular Code

var app = angular.module("app", [])
.controller("controller", function ($scope, WebFactory) {
$scope.data = "data";
$scope.error = "error";
$scope.data=WebFactory.getData();

})
.factory("WebFactory", function ($http) {
var obj = {};

obj.getData = function()
{
$http({
method: "GET",
url: "http://localhost:37103/api/employee",
}).then(function success(response) {
return response.data;
})
.then(function error(response) {
return response;
});
return 'No data';
}
return obj;

});


HTML code

<body ng-controller="controller">

data: {{data}}
<br/>
error: {{error}}
<br />




I have spent 2 days, but still dont know why its not working.

Answer

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(function success(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;
            });