Store data from controller to service in angularjs

97 views Asked by At

Although there are many questions regarding the subject , yet I am unable to figure it out , how to proceed further.

I am new in AngularJS. I want to pass data coming from API in Controller and pass it to another function. For this I know I have to create a Service. But after coming to this extend of code I am unable to figure it, how to store it in Service and pass it on other Controller or of function within same Controller. I am new in making Service.

Controller:

 $scope.GetR = function (){           

             $scope.X = null;
             $scope.Y = null;

        $http({method: 'POST', url: 'http://44.43.3.3/api/infotwo', 
                          headers: {"Content-Type": "application/json"}, 
                          data: $scope.ResponseJson 
          })
        .success(function(data, status, headers, config) {
             $scope.X = data.X;
             $scope.Y = data.Y;
            //console.log($scope.X+"and"+$scope.Y);

             //Seding RS to API to get AAs 
                        $scope.RJson = {
                            "ICl": $scope.ICl,
                            "RS":  $scope.X
                        };

                        $http({method: 'POST', url: 'http://44.128.44.5/api/apithree', 
                                  headers: {"Content-Type": "application/json"}, 
                                  data: $scope.RJson 
                              })
                            .success(function(data, status, headers, config) {
                                 $scope.At = data;
                                 $scope.Eq = data.AA.Eq;
                                 $scope.FIn = data.AA.FIn;
                                 $scope.MM = data.AA.MM;


                                console.log("Eq:"+$scope.Eq+"       FIn:"+$scope.FIn+"       MM:"+$scope.MM);
                            }).error(function(data, status, headers, config) {   
                                console.log("API failed...");
                            }); 

        }).error(function(data, status, headers, config) {   
            console.log("Something went wrong...");
        }); 

   };

Now I want to pass this data to Service so that I can call this output on other API input

.success(function(data, status, headers, config) {
                                 $scope.At = data;
                                 $scope.Eq = data.AA.Eq;
                                 $scope.FIn = data.AA.FIn;
                                 $scope.MM = data.AA.MM;

                                console.log("Eq:"+$scope.Eq+"       FIn:"+$scope.FIn+"       MM:"+$scope.MM);
2

There are 2 answers

1
korteee On

This shows how to create a service and share data between two controllers.

The service:

(function() {
    'use strict';

    angular
        .module('myAppName') // Replace this to your module name
        .service('MyService', MyService);

    MyService.$inject = [];

    function MyService() {
        this.data = null;
    }
})();

First controller:

(function() {
    'use strict';

    angular
    .module('myAppName') // Replace this to your module name
        .controller('MyFirstController', MyFirstController);

    MyFirstController.$inject = ['MyService', '$http'];
    function MyFirstController(MyService, $http) {
        var vm = this;
        vm.data = MyService.data;

        $http.post('/someUrl', whatEverData).then(resp=> {
            MyService.data = resp.data;
        })

    }
})();

Second controller:

(function() {
    'use strict';

    angular
    .module('myAppName') // Replace this to your module name
        .controller('MySecondController', MySecondController);

    MySecondController.$inject = ['MyService', '$http'];
    function MySecondController(MyService, $http) {
        var vm = this;
        vm.data = MyService.data; // Here you can use the same data


    }
})();
8
Gaara On

Not sure if this is what you are looking for. Below code is not tested (May have syntax errors)

Service:

function() {
  'use strict';

  angular
    .module('myAppName')
    .factory('MyService', MyService);

  MyService.$inject = [];

  function MyService() {
    var data = null;
    return {
      getData: function() {
        return data;
      },
      setData: function(d) {
        data = d;
      }
    }
  }
})();

Controller:

(function() {
  'use strict';

  angular
    .module('myAppName')
    .factory('controller', controller);

  controller.$inject = ['$scope', '$http', 'MyService'];

  function controller($scope, $http, MyService) {
    $scope.GetR = function() {

      $scope.X = null;
      $scope.Y = null;

      var promise = $http({
        method: 'POST',
        url: 'http://44.43.3.3/api/infotwo',
        headers: {
          "Content-Type": "application/json"
        },
        data: $scope.ResponseJson
      });

      promise.success(function(data, status, headers, config) {
        $scope.X = data.X;
        $scope.Y = data.Y;
        //console.log($scope.X+"and"+$scope.Y);

        //Seding RS to API to get AAs 
        $scope.RJson = {
          "ICl": $scope.ICl,
          "RS": $scope.X
        };

      }).error(function(data, status, headers, config) {
        console.log("Something went wrong...");
      });

      return promise;
    };

    $scope.sendRS = function() {
      var promise = $http({
        method: 'POST',
        url: 'http://44.128.44.5/api/apithree',
        headers: {
          "Content-Type": "application/json"
        },
        data: $scope.RJson
      });

      promise.success(function(data, status, headers, config) {
        $scope.At = data;
        $scope.Eq = data.AA.Eq;
        $scope.FIn = data.AA.FIn;
        $scope.MM = data.AA.MM;

        console.log("Eq:" + $scope.Eq + "       FIn:" + $scope.FIn + "       MM:" + $scope.MM);
      }).error(function(data, status, headers, config) {
        console.log("API failed...");
      });
      return promise;
    }

    var init = function() {
      $scope.GetR().then(function() {
        $scope.sendRS().then(function(data) {
          MyService.setData({
            At: data,
            Eq: data.AA.Eq,
            FIn: data.AA.FIn,
            MM: data.AA.MM
          });
        })
      })
    }

    init();
  }
})();

Other controller

(function() {
  'use strict';

  angular
    .module('myAppName')
    .controller('controller1', controller1);

  controller1.$inject = ['$scope', 'MyService'];

  function controller1($scope, MyService) {
    $scope.data = MyService.getData();
  }
})();