2016-10-13 10 views
0

저는 angularjs를 처음 사용하여 몇 가지 질문을하고 싶습니다. 서버에서 양식 객체를 가져와야하는 프로젝트에서 작업하고 있습니다. 이 양식은 여러 개의 레이어가있는 복잡한 트리 개체이며 4 개의 다른 구성 요소/탭을 만들어 해당 개체에 바인딩합니다. 데이터를 얻기 위해 서비스를 만들었습니다. Angularjs 1.5.x는 구성 요소 간의 서비스와 데이터를 공유합니다.

angular.module('myService', ['restangular']) 
     .factory('FormService', ['Restangular', '$q', function(Restangular, $q) { 

    function FormService() { 
     var self = this; 
     self.form = null; 

     self.getForm = function getForm(id) 
     { 
      var deferred = $q.defer(); 
      if (self.form !== null) 
      { 
       deferred.resolve(self.form); 
       console.log("Cache!"); 
      } 
      else { 
       Restangular.one('form', id).get() 
        .then(function successCallback(response) 
        { 
        self.form = response; 
        deferred.resolve(response); 
        console.log("from server!"); 

        }, function errorCallback(response) { 
        deferred.reject(response); 
        console.log("error, cannot resolve object"); 
        }); 
      } 
      return deferred.promise; 
     } 

     return new FormService(); 
    }]) 
}); 

는 그럼 난 내 구성 요소를 가지고 아래에 비슷한 설정을 가진 모든 : "캐시"

angular.module('page1Summary', ['formService']).component('page1Summary', { 
    templateUrl: 'page1-summary/page1-summary.template.html', 
    controller: ['FormService', function Page1SummaryController(FormService) { 
    var ctrl = this; 

    // ******* Init Params Start *********** // 
    this.$onInit = function() { 
     // init value when object ready 
     FormService.getForm() 
     .then(
      /* on success */ 
      function successCallback(data) { 
      console.log("page1-summary init"); 
      ctrl.form = data; 
      console.log("page1-summary got the data"); 
     }, 
      /* on error */ 
      function errorCallback(data) 
      { 
       console.log("failed to get form"); 
      } 
    ); 
    } 

    /* other stuff here */ 
} 

내가 하나를 인쇄했다 또는 "서버로부터"getForm 서비스. 그래서 내가 서버 또는 메모리에서 데이터를 가져 오는지 알아낼 수 있습니다. 그러나 새로 고침 할 때마다 결과가 다릅니다. 때로는 서비스의 로컬 변수에 저장된 데이터가 "캐싱"되었지만 때로는 일부 페이지가 "서버에서"데이터를 가져옵니다.

나는 무엇이 잘못되었는지 알고 싶습니다. 서비스가 서버에서 처음으로 시작될 때만 생각했지만 실제로 그렇지 않은 것 같습니다.

누군가 나를 도울 수 있고 내가 잘못 한 것을 지적 할 수 있습니까?

미리 감사드립니다.

답변

0

결과를 self.form에 캐싱하고 있습니다. FormSerivce 공장 구성원. self.form이 다시 변수입니다. 페이지를 새로 고칠 때까지 결과를 캐시합니다. 페이지를 새로 고침 후 self.form의 값은 응용 프로그램의 다른 모든 변수와 마찬가지로 재설정됩니다.

캐시하려는 결과가 self.form 인 경우 localstorage에 캐시하십시오. 페이지를 새로 고친 후에도 결과를 다시 얻을 수 있습니다.