我正在使用TypeScript AngularJS本地存储服务来访问IndexedDB。 实现open()函数以打开与IndexedDB的连接,并将数据库实例分配给IDBDatabase类型的变量 database (this.database)
当我指定:
this.database =(event.target as IDBOpenDBRequest).result
我确认 this.database 包含数据库的实例。 但问题是 - 当我从控制器调用getForms()时, this.database 未定义:(
请告知为什么会发生这种情况以及如何解决这个问题。谢谢。
以下是我服务的代码:
namespace App {
"use strict";
export class LocalStorage {
indexedDB: IDBFactory;
dbName: string;
tableName: string;
lastIndex: number;
database: IDBDatabase;
static $inject: string[] = ["$window", "$q"];
constructor(private $window: ng.IWindowService, private $q: ng.IQService) {
this.indexedDB = $window.indexedDB;
this.lastIndex = 0;
this.dbName = "entities";
this.tableName = "keyvaluepairs";
}
open() {
var deferred = this.$q.defer();
var request = this.indexedDB.open(this.dbName);
request.onsuccess = function (event: Event) {
this.database = (event.target as IDBOpenDBRequest).result;
deferred.resolve();
};
request.onerror = function (event: Event) {
deferred.reject();
};
return deferred.promise;
};
getForms() {
var deferred = this.$q.defer();
// Problem here: this.database for some reason is undefined,
// although I have instantiated it in the open() function
if (this.database) {
// my code comes here...
}
return deferred.promise;
};
}
app.service("LocalStorage", LocalStorage);
}
以下是我的控制器的代码:
namespace App {
"use strict";
/**
* DetailController
*/
class DetailController {
id: number = 15424420;
form: any;
message: string;
static $inject: string[] = ["LocalStorage", "$filter"];
constructor(private localStorage: LocalStorage, private $filter: ng.IFilterService) {
this.localStorage.open().then(
response => this.getForms(),
response => this.error(response));
}
getForms() {
this.localStorage.getForms().then(
response => this.success(response),
response => this.error(response));
}
// Apply filter to find the form we need by ID
success(data) {
this.form = this.$filter("filter")(data, { Id: this.id })[0];
this.message = this.form.Name;
}
error(response) {
this.form = null;
this.message = response.error.statusText;
}
}
app.controller("DetailController", DetailController);
}