2017-06-06 38 views
1

我正在使用使用Angular2的IndexedDB。 爲此,我正在關注下面的github 鏈接。 https://github.com/gilf/angular2-indexeddb在Angular2中將值插入IndexedDB

我正在創建這樣的數據庫。

 ngOnInit(){ 
    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 }); 

       }); 

     } 

但是,當我試圖插入值的UserDetails表,未working.For插入我使用下面的代碼。

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

誰能告訴我哪兒我做wrong.I很新的這angular2,IndexedDB的。請幫助我。

+0

你是什麼意思'不工作'?你有錯誤信息嗎?什麼都沒發生? – Francesco

+0

是@Francesco我得到這樣的錯誤。 在查詢之前,您需要使用createStore函數來創建數據庫! 現在解決了。編寫代碼時我犯了一些錯誤。 – ananya

+0

你做了這個'db = new AngularIndexedDB('myAppDb',1);'? –

回答

0

createStore,現在openDatabase是異步方法。所以,下面會工作。

ngOnInit(): void { 
    let db: AngularIndexedDB = new AngularIndexedDB('myDb', 1); 
    db.openDatabase(1, (evt) => { 
     let objectStore = evt.currentTarget.result.createObjectStore(
     'people', { keyPath: 'id', autoIncrement: true }); 

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

    }).then(function() { 

     db.add('people', { name: 'nameq', email: 'email' }).then(() => { 
     // Do something after the value was added 
     }, (error) => { 
      console.log(error); 
     }); 
    }); 

    db.openDatabase(1).then(function() { 
    db.getAll('people').then((person) => { 
     console.log(person); 
     }, (error) => { 
     console.log(error); 
     }); 
    }); 
    }