Getting error while adding value to indexedDB usin

2019-09-16 10:51发布

问题:

I am using IndexedDB using Angular2. For that i am following the below github link. https://github.com/gilf/angular2-indexeddb

I am creating db like this and adding value like this.

    ngOnInit(){

        let db = new AngularIndexedDB('mydb', 1);
        db.createStore(1, (evt) => {
            let objectStore = evt.currentTarget.result.createObjectStore(
                'Userdetails', { keyPath: "id", autoIncrement: true });

            objectStore.createIndex("name", "name", { unique: false });
            objectStore.createIndex("email", "email", { unique: true });

        });


db.add('Userdetails', { name: 'name', email: 'name@mail.com' }).then(() => {
    // Do something after the value was added
     console.log('fields added');
}, (error) => {
    console.log('error is'+error);
});

}

But in console i am getting error like this.You need to use the createStore function to create a database before you query it!

Can anyone please tell me where exactly i am doing wrong.I am very new to this angular2-indexeddb.Please help me.

回答1:

I think your code for db.add is fired to early if i'm reading the code correctly.

If you change it to it should work

 db.createStore(1, (evt) => {
        let objectStore = evt.currentTarget.result.createObjectStore(
            'Userdetails', { keyPath: "id", autoIncrement: true });

        objectStore.createIndex("name", "name", { unique: false });
        objectStore.createIndex("email", "email", { unique: true });

}).then(() => {
    db.add('Userdetails', { name: 'name', email: 'name@mail.com' }).then(() => {
        // Do something after the value was added
        console.log('fields added');
    }, (error) => {
        console.log('error is'+error);
    });
});