Search code examples
angularjsangularjs-controllerangularjs-factoryangularjs-http

$http service in Factory returns undefined in AngularJS


I am new in angularJS and try to make a CRUD operation to clear my concept. I try to use angular factory but I google a lot and unable to find any solution on below concept. I just want to use my factory in controller which is not working for me.

Factory :

(function () {
'use strict';

 angular
.module('app', [])
.factory("crudFactory", function (path, myObj) {
     return {
         AddObject: function (path)
         {
             $http({
                 method: "POST",
                 url: path,
                 params: { myObj : myObj }
             }).then(function mySuccess(response) {
                 return response.data;
             }, function myError(response) {
                 return "Error Found :" + response.statusText;
             });
         },
         first: function () {
             return "";//
         }
     };
});
})();

I want to use this factory in controller but its not working.

Controller :

(function () {
'use strict';
debugger;
  angular
 .module('app')
 .controller('BusinessProfileCtrl', BusinessProfileCtrl);

function BusinessProfileCtrl($scope, crudFactory) {
    debugger;
    var vm = this; //vm = view model
    function Save() {
        debugger;
        var businessObj = {
            Id:vm.Id,
            Name: vm.Name,
        };
        var abc = crudFactory.AddObject("http://localhost:63358/BusinessUnit/Post", businessObj);
    }
    vm.Save = Save;
}
 })();

Hope will get any help. Thanks in advance.


Solution

  • in factory just return the http promise and from the controller catch that promise.

    modify the factory like this;

    .factory("crudFactory", function() {
        return {
            AddObject: function(path,myObj) {
                return $http({
                    method: "POST",
                    url: path,
                    params: {
                        myObj: myObj
                    }
                })
            },
            first: function() {
                return ""; //
            }
        };
    });
    

    in the controller catch the promise like this

    var abc;
    crudFactory.AddObject("http://localhost:63358/BusinessUnit/Post", businessObj).then(function mySuccess(response) {
        abc = response.data;
    }, function myError(response) {
        abc = "Error Found :" + response.statusText;
    });