1. 程式人生 > >ionic 通過PouchDB + SQLite來實現app的本地儲存(Local Storage)

ionic 通過PouchDB + SQLite來實現app的本地儲存(Local Storage)

程式碼書寫格式上不一樣!

1.ionic是跨平臺app開發的工具(Cordova)的一個框架!

2.PouchDB是操作SQLite資料庫的javascript庫(跟mongoose操作mongodb一樣)!

3.SQLite是一種輕量級的嵌入式資料庫(資料庫不需要你安裝的,手機系統自帶,你需要安裝的就是SQLite外掛)!

第一步 :安裝Cordova 和 ionic 命令如下:

npm install -g cordova ionic

第二步:建立工程 命令如下:

ionic start birthday

第三步:安裝SQLite外掛和pouchdb.js庫,並將pouchdb引入到index.html中。

//安裝SQLite外掛
cordova plugin add io.litehelpers.cordova.sqlitestorage
 
//安裝pouchdb庫
bower install pouchdb
 
//在index.html引入pouchdb
<script src="lib/pouchdb/dist/pouchdb.min.js"></script>

第四步:環境基本OK了!接下來開始寫程式碼了! 首先配置service你也可以用factory,我用的service。在www/js/services.js 末尾去掉分號,新增一下程式碼。

.service('birthday', function () {
  var _db;
  //dateFix 函式是用來處理SQLite讀出的資料的,因為SQLite的儲存的資料結構層次優點不同,
  //感興趣的同學可以把資料打印出來研究下
  function dateFix (result) {
    var data = [];<br>  result.forEach(function (each) {<br>    data.push(each.doc);<br>  });
    return data
  };
 
  return {
    initDB: function () {
      _db = new PouchDB('birthday', {adapter: 'websql'});
    },
    getAllBirthday: function (callback) {
      _db.allDocs({include_docs: true}).then(function (result) {
        callback(dateFix(result.rows));
      })
    },
    addBirthday: function (birthday) {
      _db.post(birthday);
    },
    removeBirthday: function (birthday) {
      _db.remove(birthday);
    }
  }
});

第五步:專案啟動時我們要初始化資料庫,所以我們在.run()方法裡初始化資料庫; 有顏色的地方就是加的程式碼,第一處時注入我們之前定義的service(‘birthday’)。現在注入進去。第二處表示$ionicPlatform準備好之後初始化資料庫。

.run(function($ionicPlatform, birthday) {
  $ionicPlatform.ready(function() {
    birthday.initDB();
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
 
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleLightContent();
    }
  }

第六步:開始controller裡和views裡的程式碼了 工程中的路由都已經配置好了,我們直接修改她的controller和views就行了! 展示生日我們用tab-dash.html, 對應的controller是DashCtrl; tab-dash.html中的程式碼修改如下:

<ion-view view-title="Dashboard">
  <ion-content class="padding">
    <div class="list card" ng-repeat="birthday in birthdays">
      <div class="item item-divider">{{birthday.date}}</div>
      <div class="item item-body">
        <div>
          {{birthday.name}}
        </div>
      </div>
    </div>
  </ion-content>
</ion-view>

DashCtrl中修改如下:

.controller('DashCtrl', function($scope, birthday) {
  $scope.birthdays = [];
  $scope.init = function () {
    birthday.getAllBirthday(function (data) {
      console.log(data);    //還沒儲存資料目前列印的是空陣列
      $scope.birthdays = data;
    })
  };
  $scope.init();
})

第七步:開始儲存資料頁面的controller和views編寫了! 儲存資料的頁面就用tab-account.html, controller就用AccountCtrl。 tab-account.html的頁面程式碼改成這樣。

<ion-view view-title="Account">
  <ion-content>
    <ion-list>
    <div class="row">
        <div class="col col-100" style="height:100px;"></div>
    </div>
    <div class="row">
        <div class="col col-10">{{name}}</div>
        <div class="col col-80"></div>
        <div class="col col-10">{{date}}</div>
    </div>
    <div class="row">
        <div class="col col-20">
            姓名:
        </div>
        <div class="col col-80">
            <input type="text" ng-model="a.name" style="border:1px solid black"  >
        </div>
    </div>
    <div class="row">
        <div class="col col-20">
            生日:
        </div>
        <div class="col col-80">
            <input type="text" ng-model="a.date" style="border:1px solid black" >
        </div>
    </div>
    <div class="row">
        <div class="col col-20"></div>
        <div class="col col-20">
            <button ng-click="psotBirthday()">儲存</button>
        </div>
        <div class="col col-60"></div>
    </div>
    </ion-list>
  </ion-content>
</ion-view>

接下來修改AccountCtrl 程式碼改成這樣:

.controller('AccountCtrl', function($scope, birthday) {
  $scope.a = {}
  $scope.psotBirthday = function () {
    console.log($scope.a);
    if (!$scope.a.name && !$scope.a.date) {
      alert("姓名和日期不能為空!");
      return;
    };
    birthday.addBirthday($scope.a);
    $scope.a.name = '';
    $scope.a.date = '';
  }
});

OK到現在,我已經把通過pouchdb和SQLite在手機本地儲存資料,取出資料的過程已經演示完成。至於刪除也很簡單的。 我相信你可以自己去檢視官方文件,自己去實現的! pouchdb官方API地址:http://pouchdb.com/api.html#delete_document

//草稿箱
  service.factory('myDraftBox', function () {
    var _db;
    //dateFix 函式是用來處理SQLite讀出的資料的,因為SQLite的儲存的資料結構層次優點不同,
    //感興趣的同學可以把資料打印出來研究下
    function dateFix(result) {
      var data = []; 
      result.forEach(function (each) {
        data.push(each.doc);
      });
      return data;
    }
  
    return {
      initDB: function () {
        _db = new PouchDB('myDraftBox', { adapter: 'websql' });
      },
      getAllDraftBox: function (callback) {
        _db.allDocs({ include_docs: true }).then(function (result) {
          callback(dateFix(result.rows));
        });
      },
      addDraftBox: function (myDraftBox) {
        _db.post(myDraftBox);
      },
      removeDraftBox: function (myDraftBox) {
        _db.remove(myDraftBox._id, myDraftBox._rev);
      }
    }
  });