Search code examples
angularjsangularjs-scopeangular-services

Data getting overwritten or corrupted. What is the reason?


Here is my code for the controller and the service. I am using AngularJS v1.6

app.controller('ServicesCtrl',['$scope','$http','DataService',function($scope,$http,DataService){

 $scope.returnedData = DataService.GetData('services1.json'); 
}]);

app.controller('ContactCtrl',['$scope','$http','DataService',function($scope,$http,DataService){

 $scope.returnedData = DataService.GetData('location.json'); 
// console.log($scope.returnedData);
}]);

app.service('DataService', ['$http', function($http){
 var data;
 this.GetData = function(path) {
   $http.get(path).then(function(response){
    //console.log(response.data);
   data = response.data;
  });
  return data;
 };
}]);

Why is my data getting corrupted on return to the controller function. I am getting an unexpected property of $$hashkey with the value of an object(12). I am a beginner so kindly explain in easy terms. I am able to log out the correct data inside the DataService but it gets corrupted inside the controller. The data of both the controller just gets mixed in the view. Even if I don't use one of the controller, the other one is not working as expected.


Solution

  • you need to call like below: Promise will resolve and it will provide data in your controller. checkout working plunker

    app.controller('ServicesCtrl', ['$scope', '$http', 'DataService', function($scope, $http, DataService) {
    
          DataService.GetData('services1.json').then(function(response) {
            $scope.returnedData = response.data;
          });
        }]);
    
        app.controller('ContactCtrl', ['$scope', '$http', 'DataService', function($scope, $http, DataService) {
    
          DataService.GetData('location.json').then(function(response) {
            $scope.returnedData = response.data;
          });
        }]);
    
        app.service('DataService', ['$http', function($http) {
          var data;
          this.GetData = function(path) {
            return $http.get(path)
          };
        }]);