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);
6
  • You want to store to service this variables: $scope.At, $scope.Eq, $scope.FIn and $scope.MM? Commented Sep 6, 2017 at 8:19
  • This link might help. Sharing data between two controllers with service. (watchers are used for 2 way data binding) Commented Sep 6, 2017 at 8:46
  • @CommercialSuicide yes , I want to pass these data to Service as it will be needed on another controller API POST Commented Sep 6, 2017 at 8:50
  • @Gaara before sharing I want to pass those $scope variables data to service. Please suggest according to my controller Commented Sep 6, 2017 at 9:28
  • @WhoAmI, did you find a solution in answers below? Commented Sep 6, 2017 at 11:28

2 Answers 2

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


    }
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please edit your answer according to my requirements.
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();
  }
})();

8 Comments

app.controller('Ctrl', ["$scope", "$timeout", "$http", "$interval", "$state", "Xservice", function ($scope, $timeout, $http, $interval, $state, Xservice) { . This is my starting part of the controller
I guess it will be .controller instead of .factory in .factory('controller1', controller1);
@WhoAmI Updated the answer
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 did you initialise your module angular.module('myModule', []) ? Can you share a plunker link where this issue is reproducible?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.