2015-12-07 47 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 –