事务仅找到在使用 2 object 个存储初始化 IndexedDB 后创建的第一个 object 个存储

Transaction finds only 1st object store created after initializing IndexedDB with 2 object stores

我发现有几篇帖子询问是否以及如何在单个 IndexedDB 数据库中创建多个 object 存储。我认为那不是我真正的问题。我在单个 onupgradeneeded 事件中创建了 2 object 个商店,我在 Google Chrome 的开发者控制台中看到了这两个商店。所以我想这行得通。

一个 object 商店存储锻炼,其他练习通过 ID 引用锻炼(我尝试将它们组合在一个 object 商店中,但更新信息时太麻烦了)。当我尝试从第一个 object 商店检索锻炼并从第二个 object 商店检索相应的练习时,应用程序无法再找到第二个 object 商店。似乎只有第一个 object 商店可用。

希望以下代码能更好地解释问题:

db.service.ts

数据库初始化:

private db: IDBDatabase;

constructor() { }

public init(): Promise<void> {
    if(this.db) {
        this.db.close();
    }
    return new Promise(resolve => {
        const req = indexedDB.open('workoutsDB', 1);
        req.onupgradeneeded = e => {
            const db = (e.target as any).result;
            const workouts = db.createObjectStore(
                'workouts', {keyPath: 'id'});
            workouts.put({id: '1', name: '5x5'});
            const exercises = db.createObjectStore(
                'exercises', {keyPath: 'id'});
            exercises.put({id: '1', workout: '1', name: 'Squats'});
            exercises.put({id: '2', workout: '1', name: 'Bench presses'});
        }
        req.onsuccess = e => {
            this.db = (e.target as any).result;
            resolve();
        }
    });
}

锻炼身体:

public getWorkout(id): Promise<Workout> {
    return new Promise<Workout>(resolve => {
        var tx = this.db.transaction('workoutsDB', 'readwrite');
        var store = tx.objectStore('workouts');  // <= THIS WORKS!!!
    });
}

获取锻炼练习:

public getExercises(workoutId): Promise<Exercise[]> {
    return new Promise<Exercise[]>(resolve => {
        var tx = this.db.transaction('workoutsDB', 'readwrite');
        var store = tx.objectStore('exercises'); // <= ERROR!!!
    });
}

函数 getWorkout(id)getExercises(workoutId) 从 Ionic 页面调用如下:

workout.page.ts

workout: Workout;
exercises: Exercises[] = [];

constructor(private db: DbService) { }

ngOnInit() {
    var id = this.route.snapshot.paramMap.get('id');
    this.db.init().then(() => getWorkout(id));
}

getWorkout(id) {
    this.db.getWorkout(id).then(workout => {
        this.workout = workout;
        this.db.getExercises(id).then(exercises => {
            this.exercises = exercises;
        });
    });
}

我不确定我做错了什么。显然,获得练习需要我首先检索相应的练习。我想也许不同的交易之间存在冲突之类的,但我无法解决 pin-point 这个问题。

如有任何帮助,我们将不胜感激!

this.db.transaction 的第一个参数是错误的。它应该是您将在事务中使用的所有对象存储的名称数组(或者,如果它只是一个对象存储,它可以是仅包含该名称的字符串)。相反,您将数据库的名称放在那里。这很可能是你的错误。

如果没有,请编辑您的 post 以包含您看到的具体错误消息,这样人们可以更轻松地帮助您。或者包括一个我们可以 运行 自己观察错误的最小示例。