2015-12-22 74 views
1

我有一個具有「init」方法的服務「OneTimeService」。如何緩存角度數據?

// Within OneTimeService code 
var this = self; 
this.init = function() { 
return $http..... function(data) { 
    self.data = data 
} 
} 

裏面每個我的控制器,與我的路由相關聯的,我有: //在一些控制器代碼 OneTimeService.init(),然後(數據){$ = scope.somevariable數據.someattribute; //做別的東西 }

我的問題是,我有10個不同的「路線」。他們每個人都有的:

// Within every controller (assuming each route I have uses a different controller) code but injects the OneTimeService. 
OneTimeService.init().then(data) { 
$scope.somevariable = data.someattribute; 
// do other stuff 
} 

每次我打電話「的init()」,它執行$ HTTP請求,在現實中,我要的是能夠在我的應用$ ONE TIME EVER叫它http請求,然後使用服務中的緩存變量「self.data」。我喜歡.then的原因是保證在做其他事情之前在OneTimeService中設置「self.data」。有替代品嗎?

這樣做的最好方法是什麼?

回答

2

我緩存,我檢查,如果數據已經(從先前的呼叫)的存在與否,並使用像$ Q服務承諾上OneTimeService數據:

1 - 如果數據不存在,我會讓$ http服務調用服務器來檢索數據,然後我可以將它緩存在服務中的一個變量中。

2-如果數據確實存在,請立即使用緩存數據解決承諾並返回。

因此,像這樣:

// in OneTimeService code 

var _cachedData = null; 

this.init = function() { 
    var def = $q.defer(); 

    // check if _cachedData was already cached 
    if(_cachedData){ 
     def.resolve(_cachedData);   
    } 

    // call the server for the first and only time 
    $http.get(url).then(function(data) { 
     // cache the data 
     _cachedData = data; 
     def.resolve(_cachedData); 
    }, function(err){ 
     def.reject(err); 
    }); 
    return def.promise; 
} 

希望這有助於。