2016-07-03 1 views
1

이 앵귤러 컴포넌트 통신은 매우 새로운 개념입니다. Angular 1.5.X 버전을 사용 중이며 팩토리를 사용하여 구성 요소간에 데이터를 공유하고 있습니다. 서비스 변수 비동기 값을 특정 시간 후에 새로 고치는 한 가지 문제에 직면하고 있습니다.Angularjs 1.5 - 서비스를 이용한 컴포넌트 통신 - 비동기 변수 조작?

나는 하나의 솔루션이 범위 변수가 아닌 변수를 감시자로 설정하는 것을 이해하지만 여기서는 중요한 것을 놓치고 있다고 생각합니다. 여러분, 의견을 공유해 주시겠습니까?

이것은

function Component1Controller(Service) { 

    this.tileData ={}; 
    var self = this; 

    var promise = Service.getTileData(this.sourceUrl); 

     promise.then(function(data) { 

     self.tileData = data; 
     Service.getTileCount = data.length; 
     console.log('This is tileData : '+ Service.getTileCount); 
     }); 

    }; 

이는 것은 구성 요소 (2) 컨트롤러 코드

function Component2Controller(Service) { 

    var self = this; 

    console.log(Service.getTileCount); 
// getting getTileCount = 0; After setting timeout function of 5 second I am able to get getTileCount value 

}; 

답변

0

이다 Service.getTileCount가 갱신 요소 1 개 제어 코드를되는 Service.js 코드

Service.$inject = ['$http','$q']; 

function Service($http,$q) { 

    this.$http = $http; 
    this.$q = $q; 

}; 

Service.prototype.getTileCount = 0; 

Service.prototype.getTileData = function(Url){ 

    var deferred = this.$q.defer(); 

    this.$http.get(Url) 
     .success(function(response){ 
      Service.prototype.getTileCount = response.data.length; 
      console.log('data length :', Service.prototype.getTileCount); 
     deferred.resolve(response); 
    }); 

    return deferred.promise; 
}; 

인 비동기 적으로, 그 이유는 처음에는 0이고 그 다음에는 일부 PO int 변경됩니다. 서비스를 간소화하고 항상 데이터 소스 인 getTileData 방법으로 작업 할 것을 권장합니다. 구현은 간단 될 것입니다 : 그것은 "개인"_tileData 속성 응답 타일 캐시 방법

function Service($http, $q) { 
    this._tileData = null; 
    this.$http = $http; 
    this.$q = $q; 
} 

Service.prototype.getTileData = function(Url) { 

    if (!this._tileData) { 
    this._tileData = this.$http.get(Url).then(function(response) { 
     return response.data; 
    }.bind(this)); 
    } 

    return this._tileData; 
}; 

참고. Service.getTileCount가 더 이상 필요하지 않습니다이 경우

function Component1Controller(Service) { 

    this.tileData = {}; 
    var self = this; 

    Service.getTileData(this.sourceUrl).then(function(data) { 
    self.tileData = data; 
    console.log('This is tileData:', self.tileData.length); 
    }); 
}; 

function Component2Controller(Service) { 
    var self = this; 
    Service.getTileData(this.sourceUrl).then(function(data) { 
    console.log('tile count', data.length); 
    }); 
}; 

: 지금 당신은 항상 당신이 그것을 호출 할 때 데이터를 상관없이 반환됩니다 getTileData 방법에 의존 할 수 있습니다.

데모 : 귀하의 의견http://plnkr.co/edit/3zE6VL4emXaLRx2nCRih?p=info

+0

감사합니다. 나는 동일한 접근법을 시도했지만 두 가지 컴포넌트 서비스 호출에서 이걸 얻고있다. 서비스의 _tileData는 null이다. 그래서 우리는 this._tileData 객체 값을 저장할 수 없다고 생각합니다. 그래서 다음 호출에서 null이 다시 발생합니다. 기본적으로 우리는 $ HTTP 서비스를 두 번 치는 것이 좋은 해결책이 아닙니다. – Samir

+0

물론, 아니오, 내 솔루션의 요점은 당신이 결코 하나 이상의 요청 (서비스 캐시 데이터)을 만들지 않는다는 것입니다. 그리고 여러분이 어떤 구성 요소로부터 getTileData를 요청했는지에 상관없이 항상 예측 가능한 방식으로 데이터를 얻을 것입니다. – dfsq

+0

그러나 내 코드에서 오류가 발견되면 상황에 맞는 업데이트 된 버전을 확인하십시오. – dfsq

관련 문제