如何离线

时间:2015-12-07 06:18:58

标签: angularjs ionic-framework ionic

我正在撰写博客应用。我想在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;
            },

    }

这是退缩的结果。

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

我不知道该如何处理。请帮助。

由于

1 个答案:

答案 0 :(得分:2)

大多数离线应用程序使用本地存储作为缓存,并在有可用连接的情况下更新。

一种简单的方法是:

  1. 从本地存储中抓取文章并将其分配给$ scope变量(这可能是未定义的)
  2. 从服务器正常请求文章
  3. 成功回调后,覆盖本地存储并重新分配范围变量。
  4. 示例代码:

    // 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

相关问题