我正在尝试在我的离子2应用程序中使用lokijs。我可以使用lokijs.js。 当试图坚持使用适配器我不能。我准备好了lokijs-cordova-fs-adapter可以使用。但是当我在我的应用程序中引用它时如下所示:得到一个无法找到它的错误。
var LokiCordovaFSAdapter = require("./cordova-file-system-adapter");
尝试在我的index.html中添加它并尝试在我的ts文件中创建适配器,如下所示:
var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});
在这种情况下出现语法错误。有人可以举例说明如何使用它吗?
答案 0 :(得分:2)
Ciao,这适用于Ionic 2,所以一步一步(我在service内做了这个):
检查是否已安装两个依赖项:
npm install lokijs --save
npm install loki-cordova-fs-adapter --save
声明并导入以下内容(在类声明之前):
declare var require: any;
var loki = require('lokijs');
var LokiCordovaFSAdapter = require("loki-cordova-fs-adapter");
var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});
在服务类中使用以下内容:
db: any; // LokiJS database
pandas: any; // our DB's document collection object
constructor() {
console.log("* inicializando...");
this.db = new loki('pandas.db', {
autoload: true,
autoloadCallback: function() {
console.log("* database loaded...")
},
autosave: true,
autosaveInterval: 10 * 1000, //every 10 seconds
adapter: adapter
});
}
使用它(此代码也在服务类中):
load() {
let collection = this.db.getCollection('pandas');
if (collection == null) {
this.pandas = this.db.addCollection('pandas');
} else {
this.pandas = collection;
}
}
pandaKamasutra() {
console.log("* Save the pandas...");
for (let i=0; i < 100; i++)
this.pandas.insert({ name: 'Panda ' + (i+1), surename: "Whurgh " + i });
}
showPandas() {
var results = this.pandas.find({});
for (let r of results)
console.log(`% id: ${r.$loki}, Panda: ${r.name}`);
}
我今天下午解决了这个问题,在游过LokiJS和lokijs-cordova-fs适配器代码后,我在Ionic文档here中找到了'light'。
希望它也适合你。 =]
答案 1 :(得分:-1)
请参阅https://github.com/cosmith/loki-cordova-fs-adapter/issues/15上的帖子,了解如何在Ionic2中执行此操作(此处重新发布)。
我终于在Ionic2应用程序(带有打字稿)中运行了这个程序。请务必安装插件cordova-plugin-file
。然后使用底部的适配器,就像Ionic2中的普通Provider一样(我已将它安装在我项目的/src/lib/loki-cordova-fs-adapter
中 - 命名为index.ts
)。
对于使用,这是一个例子:
import { Injectable } from '@angular/core'
import { Platform } from 'ionic-angular'
import * as Loki from 'lokijs'
import * as LokiIndexedAdapter from 'lokijs/src/loki-indexed-adapter'
import { LokiCordovaFSAdapter } from 'lib/loki-cordova-fs-adapter'
const DATABASE_NAME: string = 'yourFilename.db.json'
@Injectable()
export class DatabaseProvider {
private lokiOptions: any = {
verbose: true,
autosave: true,
autosaveInterval: 60000,
autoload: true
}
private db: any
public constructor (private platform: Platform, private mobileAdapter: LokiCordovaFSAdapter) {}
public load (successCallback: any): void {
if (this.db) {
successCallback()
} else {
this.db = this.loadDatabase(DATABASE_NAME, successCallback)
}
}
private loadDatabase (databaseName: string, successCallback: any): any {
this.lokiOptions.autoloadCallback = successCallback
if (this.platform.is('cordova')) {
this.lokiOptions.adapter = this.mobileAdapter
} else {
this.lokiOptions.adapter = new LokiIndexedAdapter()
}
return new Loki(databaseName, this.lokiOptions)
}
}
这是适配器:
import { Injectable } from '@angular/core'
class LokiCordovaFSAdapterError extends Error {}
// const TAG: string = '[LokiCordovaFSAdapter]'
declare var window: any
declare var cordova: any
@Injectable()
export class LokiCordovaFSAdapter {
private options: any
public constructor () {
this.options = {'prefix': 'loki'}
}
public saveDatabase (dbname: string, dbstring: string, callback: any): any {
// console.log(TAG, 'saving database')
this._getFile(dbname,
(fileEntry) => {
fileEntry.createWriter(
(fileWriter) => {
fileWriter.onwriteend = () => {
if (fileWriter.length === 0) {
const blob: any = this._createBlob(dbstring, 'text/plain')
fileWriter.write(blob)
callback()
}
}
fileWriter.truncate(0)
},
(err) => {
// console.log(TAG, 'error writing file', err)
throw new LokiCordovaFSAdapterError('Unable to write file' + JSON.stringify(err))
}
)
},
(err) => {
// console.log(TAG, 'error getting file', err)
throw new LokiCordovaFSAdapterError('Unable to get file' + JSON.stringify(err))
}
)
}
public loadDatabase (dbname: string, callback: any): void {
// console.log(TAG, 'loading database')
this._getFile(dbname,
(fileEntry) => {
// console.log('got database file')
fileEntry.file((file) => {
const reader: FileReader = new FileReader()
reader.onloadend = (event: any) => {
const contents: any = event.target.result
if (contents.length === 0) {
// console.log(TAG, 'database is empty')
callback(null)
} else {
// console.log('sending back database')
callback(contents)
}
}
reader.readAsText(file)
}, (err) => {
// console.log(TAG, 'error reading file', err)
callback(new LokiCordovaFSAdapterError('Unable to read file' + err.message))
})
},
(err) => {
// console.log(TAG, 'error getting file', err)
callback(new LokiCordovaFSAdapterError('Unable to get file: ' + err.message))
}
)
}
public deleteDatabase (dbname: string, callback: any): void {
window.resolveLocalFileSystemURL(cordova.file.dataDirectory,
(dir) => {
const fileName: string = this.options.prefix + '__' + dbname
dir.getFile(fileName, { create: true },
(fileEntry) => {
fileEntry.remove(
() => {
callback()
},
(err) => {
// console.log(TAG, 'error delete file', err)
throw new LokiCordovaFSAdapterError('Unable delete file' + JSON.stringify(err))
}
)
},
(err) => {
// console.log(TAG, 'error delete database', err)
throw new LokiCordovaFSAdapterError(
'Unable delete database' + JSON.stringify(err)
)
}
)
},
(err) => {
throw new LokiCordovaFSAdapterError(
'Unable to resolve local file system URL' + JSON.stringify(err)
)
}
)
}
private _getFile (name: string, handleSuccess: any, handleError: any): void {
// console.log(TAG, 'Retrieving file: ' + name)
window.resolveLocalFileSystemURL(cordova.file.dataDirectory,
(dir) => {
const fileName: string = this.options.prefix + '__' + name
dir.getFile(fileName, { create: true }, handleSuccess, handleError)
},
(err) => {
throw new LokiCordovaFSAdapterError(
'Unable to resolve local file system URL' + JSON.stringify(err)
)
}
)
}
// adapted from http://stackoverflow.com/questions/15293694/blob-constructor-browser-compatibility
private _createBlob (data: string, datatype: string): any {
let blob: any
try {
blob = new Blob([data], { type: datatype })
} catch (err) {
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder
if (err.name === 'TypeError' && window.BlobBuilder) {
const bb: MSBlobBuilder = new window.BlobBuilder()
bb.append(data)
blob = bb.getBlob(datatype)
} else if (err.name === 'InvalidStateError') {
// InvalidStateError (tested on FF13 WinXP)
blob = new Blob([data], { type: datatype })
} else {
// We're screwed, blob constructor unsupported entirely
throw new LokiCordovaFSAdapterError(
'Unable to create blob' + JSON.stringify(err)
)
}
}
return blob
}
}