angular-indexedDB中的自定义查询

时间:2017-02-19 19:37:56

标签: angularjs indexeddb

我在我的应用程序中使用bramski/angular-indexedDB。基本的CRUD操作工作正常,但自定义查询未按预期工作。 我正在使用代码

 angular.module('myModuleName', ['indexedDB'])
      .config(function ($indexedDBProvider) {
        $indexedDBProvider
          .connection('myIndexedDB')
          .upgradeDatabase(1, function(event, db, tx){
            var objStore = db.createObjectStore('people', {keyPath: 'ssn'});
            objStore.createIndex('name_idx', 'age', {unique: false});
            objStore.createIndex('name_idx, age_idx', ['name', 'age'] , {unique: false});
    });

基本查询操作的工作方式如下

$indexedDB.openStore('people', function(x){
   var find = x.query();
   find = find.$eq('John');
   find = find.$index("name_idx");    
   x.eachWhere(find).then(function(e){
      $scope.list= e;
   });
});

在查询后产生结果。

select * from people where name='John'

但是,在上面的场景中我们如何执行自定义quires,如

select * from people where name='John' and age='25';
delete from people where name='John' and age='25';

1 个答案:

答案 0 :(得分:0)

您使用的库没有复杂的查询,但是您可以为它编写一个纯js解决方案,类似于:

首先,您需要将索引定义为:

objStore.createIndex('name_age_idx', ['name', 'age'] , {unique: false});

然后,您只能对那些与搜索结果匹配的值进行搜索查询

searchIndexedDB = function (name, age, callback) {
  var request = indexedDB.open(dbName);
  request.onsuccess = function(e) {
    var db = e.target.result;
    var trans = db.transaction(objectStoreName, 'readonly');
    var store = trans.objectStore(objectStoreName);
    var index = store.index('name_age_idx');
    var keyRange = IDBKeyRange.only([name, age]);
    // open the index for all objects with the same name and age
    var openCursorRequest = index.openCursor(keyRange);

    openCursorRequest.onsuccess = function(e) {
        let result = e.target.result;
        // first check if value is found
        if(result){
            callback(result.value); // your callback will be called per object
            // result.delete() - to delete your object
            result.continue(); // to continue itterating - calls the next cursor request
        }
    };

    trans.oncomplete = function(e) {
        db.close();
    };

    openCursorRequest.onerror = function(e) {
        console.log("Error Getting: ", e);
    };
  };
  request.onerror = myStorage.indexedDB.onerror;
}

如果您也需要索引范围,也只需将keyrange更改为:

var keyRange = IDBKeyRange.bound([name,fromAge], [value, toAge]);