2017-03-03 4 views
0

다음은 컨트롤러 및 서비스 코드입니다. 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; 
}; 
}]); 

컨트롤러 기능으로 돌아가서 데이터가 손상되는 이유는 무엇입니까? 예기치 않은 속성 인 $$hashkey이 개체의 값 (12)과 함께 나타납니다. 나는 초보자이므로 친절하게 쉽게 설명 할 수 있습니다. DataService 안에 올바른 데이터를 로그 아웃 할 수 있지만 컨트롤러 내부가 손상됩니다. 두 컨트롤러의 데이터는 뷰에서 혼합됩니다. 컨트롤러 중 하나를 사용하지 않더라도 다른 하나는 예상대로 작동하지 않습니다.

답변

0

다음과 같이 호출하면 Promise가 해결되고 컨트롤러에 데이터가 제공됩니다. 체크 아웃 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) 
     }; 
    }]); 
+0

안녕, 좋은 답변을 작동하지만 난 아직도 내가 처음에 서비스를 만든 피하기 위해 데이터에 대한 해당 요청을 만들기위한 모든 컨트롤러에 코드의 거의 동일한 금액을 작성해야합니다. 이중화를 줄이는 더 좋은 방법/방법이 있습니까? – Ravy