问题描述
我正在尝试在我的离子2应用程序中使用lokijs。我可以使用lokijs.js。
当试图坚持使用适配器时,我无法做到。我准备好了lokijs-cordova-fs-adapter可以使用。但是当我在我的应用程序中引用它时如下:得到一个无法找到它的错误。
I am trying to use lokijs in my ionic 2 app. i am able to use lokijs.js.when trying to persist using adapter i am not able to. i ready lokijs-cordova-fs-adapter can be used. but when i refer it in my app as below: getting an error that its not able to locate.
var LokiCordovaFSAdapter = require("./cordova-file-system-adapter");
尝试在我的index.html中添加它并尝试在我的ts文件中创建适配器,如下所示:
tried adding it in my index.html and tried creating adapter in my ts file as below:
var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});
在这种情况下出现语法错误。有人可以给出一个如何使用它的例子吗?
getting syntax error in this case. can someone give an example on how to use it?
推荐答案
Ciao,这适用于Ionic 2,所以一步一步(我在中进行了此操作):
Ciao, this works on Ionic 2, so step-by-step (I did this inside a service):
-
检查是否安装了两个依赖项:
Check if both dependencies are installed:
npm install lokijs --save
npm install loki-cordova-fs-adapter --save
声明并导入以下内容(在类声明之前):
Declare and import the following (before the class declaration):
declare var require: any;
var loki = require('lokijs');
var LokiCordovaFSAdapter = require("loki-cordova-fs-adapter");
var adapter = new LokiCordovaFSAdapter({"prefix": "loki"});
在服务类中使用以下内容:
Use the following inside the service class:
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
});
}
使用它(此代码也在服务类中):
Use it (this code is also inside the service class):
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文档中的光。
I spent this afternoon solving this, after swimming around both LokiJS and lokijs-cordova-fs-adapter code, I found the 'light' in the Ionic documentation here.
希望它也适合你。 =]
Hope it works for you too. =]
这篇关于如何在离子2中使用lokijs-cordova-fs-adapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!