0

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);
halfer
  • 19,824
  • 17
  • 99
  • 186
WhoAmI
  • 217
  • 1
  • 2
  • 23
  • You want to store to service this variables: `$scope.At`, `$scope.Eq`, `$scope.FIn` and `$scope.MM`? – P.S. Sep 06 '17 at 08:19
  • This link might help. [Sharing data between two controllers with service](http://unlike-minds.blogspot.in/2017/02/angularjs-share-data-between.html). (watchers are used for 2 way data binding) – Gaara Sep 06 '17 at 08:46
  • @CommercialSuicide yes , I want to pass these data to Service as it will be needed on another controller API POST – WhoAmI Sep 06 '17 at 08:50
  • @Gaara before sharing I want to pass those $scope variables data to service. Please suggest according to my controller – WhoAmI Sep 06 '17 at 09:28
  • @WhoAmI, did you find a solution in answers below? – P.S. Sep 06 '17 at 11:28
  • @CommercialSuicide Not exactly – WhoAmI Sep 07 '17 at 06:42

2 Answers2

1

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


    }
})();
korteee
  • 2,640
  • 2
  • 18
  • 24
0

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();
  }
})();
Gaara
  • 78
  • 2
  • 12
  • `app.controller('Ctrl', ["$scope", "$timeout", "$http", "$interval", "$state", "Xservice", function ($scope, $timeout, $http, $interval, $state, Xservice) {` . This is my starting part of the controller – WhoAmI Sep 07 '17 at 06:30
  • I guess it will be `.controller` instead of `.factory` in `.factory('controller1', controller1);` – WhoAmI Sep 07 '17 at 09:55
  • @WhoAmI Updated the answer – Gaara Sep 07 '17 at 09:57
  • Its not working either , throwing this error `angular.js:38 Uncaught Error: [$injector:nomod]` . The info is coming successfully to my console , using my way that I had posted. I think it is not needed to create another function for 2nd API as it is flowing within the function . Just suggest me to store those datas to service. – WhoAmI Sep 07 '17 at 10:14
  • @WhoAmI did you initialise your module `angular.module('myModule', [])` ? Can you share a plunker link where this issue is reproducible? – Gaara Sep 07 '17 at 10:20
  • I am afraid to share on Plunker as it is not a small app . I had shown one part of a controller which actually needs to share data to service.I solved the previous error now showing this `Uncaught ReferenceError: controller2 is not defined at controller2.js:4 at controller2.js:13` and `Uncaught SyntaxError: Invalid shorthand property initializer` on this part `At: data,` of `var init= funciton()` – WhoAmI Sep 07 '17 at 10:34
  • @WhoAmI the above error means that controller2 is not declared. can you share your controller2.js code?. its difficult to debug just with error messages – Gaara Sep 07 '17 at 10:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153863/discussion-between-whoami-and-gaara). – WhoAmI Sep 07 '17 at 10:48