2015-12-07 49 views
0

我正在研究博客应用程序。我还想保存SqlLite上的文章列表。我需要一次获取所有博客。 (拥有2000多个)博客。如何离线和在线离线管理数据

以下是我的控制器代码。

var promise= userService.getArticles(); 
promise.then(function(data) { 
     $scope.articles = data; 
}, function(error) { 
    console.log('Failed for some reason:' + error); 
}); 

和工厂代码是 angular.module( 'starter.controllers')

.factory('userService', function($http,$q) { 
    var articleList = []; 


return { 

      getArticles : function() { 
        var deferred = $q.defer(); 
       $http({ 
        url: "https://www.website.com/getallinfo?access_token=94529e5d", 
        data: { starLimit: 0, endLimit: 150,created_date: 0 }, 
        method: 'POST', 
        withCredentials: true, 
       }).success(function (data, status, headers, config) { 
         deferred.resolve(data); 


       }).error(function (err) { 
        deferred.reject(error); // 
       }) 
       return deferred.promise; 
      }, 

    } 

其returing结果。

我还需要将这些数据保存在sqllite中。另外我想显示数据为离线。

我不知道该如何操作。请帮助。

感谢

回答

2

大多数脱机应用程序使用本地存储作为高速缓存和更新,如果有可用的连接。

一个简单的方法来做到这一点是:

  1. 抓住从本地存储的文章,并将其分配到$ scope变量(可以是不确定的)
  2. 请求文章从正常服务器
  3. 成功的回调覆盖本地存储并重新分配范围变量。

Exampe代码:

// The article service 

myApp.factory('articles', function($q, $timeout, $window, loremIpsum) { 


    // Initialize by grabbing the articles from the local cache (if any) 

    var items = angular.fromJson($window.localStorage.getItem('myArticles')); 

    // Construct our service 

    var service = { 
    items: items, 
    refresh: function() { 

     // Sync with the server 

     var defer = $q.defer(); 

     // For this demo I'm using a timeout (this also allows for some artificial lag). 
     // Replace this with your $http calls. 

     $timeout(function() { 

     // Here I'm generating some total random items that we're resolving 
     // Also not needed in your app 

     var c = 100, result = []; 
     while (c--) { 
      result.push({ 
      title: loremIpsum.getRandomLine(2), 
      description: loremIpsum.getRandomLine(15) 
      }); 
     } 

     service.items = result; 
     defer.resolve(result); 

     // Store the returned result from the server in the local storage 

     $window.localStorage.setItem('myArticles', angular.toJson(result)); 

     }, 500); 

     return defer.promise; 
    } 
    }; 

    return service; 
}); 

Plunker例子可以发现here

+0

可以用我的示例代码以及sggin或覆盖variabke –