2015-12-22 37 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; 
} 

希望这有助于。