2016-09-05 100 views
1

我有兩個組件,我需要在兩個組件中顯示相同的數據。 我的服務:承諾服務共享數據

export default class Logs {  

    constructor($http, $q, httpService) { 
     this.$http = $http; 
     this.$q = $q; 
     this.$rootScope = $rootScope; 
     this.httpService = httpService; 
     this.logs = null; 
     this.getDefer = this.$q.defer(); 
     this.loadData(); 
    } 

    loadData() { 
     var request = {url: '/logs'}; 
     this.httpService.getJson(request) 
      .then((response) => { 
       this.logs = response.data; 
       this.getDefer.resolve(this.logs); 
      }) 
      .catch((err) => { 
       this.getDefer.reject(err); 
      }); 

     return this.getDefer.promise; 
    } 

    getLogs() { 
     return this.getDefer.promise; 
    } 

    create(newLog) { 
     return this.$http.post('http://localhost:9000/api/logs', newLog); 
    } 
} 

// this is example of using service in component 
this.logService.getLogs().then((result) => {     
    this.logs = result;    
}); 

我使用的承諾,因爲,getLogs在幾個組件使用,並幫助我避免在應用程序啓動雙重要求。但現在,我想知道,如何在更新或創建後如何調用getLogs來獲取新數據?

回答

1

你這樣做有點不對。您應該從getLogs返回承諾。

像:

getLogs() { 

    if(this.getDefer) return this.getDefer.promise; 
    this.getDefer = $q.defer(); 
    loadData().then(function(data){ 
     this.getDefer.resolve(data); 
     delete this.getDefer; 
    }); 
    return this.getDefer.promise; 

} 

和loadData:

loadData() { 
    if(this.logs) return $q.when(this.logs); //<-- return cached if exist 
    var request = {url: '/logs'}; 
    return this.httpService.getJson(request) 
     .then((response) => { 
      this.logs = response.data; 
      return response.data; 
     }); 
} 

所以loadData是私有方法,它asyncronously返回數據,並可能對其進行緩存,並getLogs應該是切入點來獲取這些數據。所以你應該在getLogs中使用延遲。如果已經有請求loadData - 返回promise,否則 - 創建新的延遲。

不幸的是我現在不能提供Plunker,但這就是概念。 :)

+0

謝謝,這是我需要的 – user348173

+0

不客氣:) – Kindzoku