컨트롤러간에 데이터를 공유하는 데 관련된 문제를 다룬 몇 가지 주제가 있지만 필자의 경우에는 좋은 답변을 찾지 못했습니다.컨트롤러 사이의 AngularJS 비동기 데이터 공유
저는 약속을 사용하여 비동기 데이터를 가져 오는 컨트롤러가 하나 있습니다. 그런 다음 컨트롤러는 해당 범위 내에서 작동하도록 데이터 사본을 만듭니다. 그런 다음 첫 번째 컨트롤러와 동일한 데이터 복사본으로 작업하기를 원하는 두 번째 컨트롤러가 있으므로 둘 다 공유합니다. getCurrentData가 다른 객체를 제공하고 올바른 변경되지 않습니다, 그래서 GetData의가 비동기로
.controller('firstController', function ($scope, someService){
var vm = this;
someService.getData().then(function(data) {
angular.copy(data, vm.data); //creates a copy and places it on scope
someService.setCurrentData(vm.data)
}
});
.controller('secondController', function ($scope, someService){
var vm = this;
vm.data = someService.getCurrentData(); //Triggers before the setter in firstController
});
.factory('someService', function(fetchService){
var _currentData = {};
var getData = function(){
return fetchService.fetchData().then(function(data) { return data; });
};
var getCurrentData = function(){
return _currentData;
}
var setCurrentData = function(data){
_currentData = data;
}
});
setCurrentData가 getCurrentData 후 트리거됩니다
다음은 예를 들어 역할을 간단하게 몇 가지 코드입니다. 나는 당신이 방송과 시계로 이것을 해결할 수 있다는 것을 알고 있지만 가능하다면 그것을 사용하는 것을 피하려고합니다.
당신은 getCurrentData (대한 비동기 API를 유지한다), getCurrentData는()() GetData의를 호출해야합니다. – eddiec