首页 > 解决方案 > 使用 Angular 7 在 IndexedDB 中添加价值

问题描述

首先,我尝试了与该主题相关的所有问题和答案。此外,我尝试了相关问题并尝试解决但没有成功。所以请仔细阅读我的问题。

首选链接

ngx-indexed-db

与链接相关的搜索

使用angular2向indexedDB添加值时出错

我想在其中添加数据,indexeddb但以某种方式显示数据库连接打开错误。我附上了一个截图。所以我要求回答一个小例子增加价值indexeddb在此处输入图像描述

我的代码

app.components.js

import { Component, OnInit } from '@angular/core';
import { NgxIndexedDB } from 'ngx-indexed-db';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'indexDb-Angular';


  ngOnInit() {
    let  db = new NgxIndexedDB('DVdb', 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 });

    });

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

}

标签: angularangular6angular7indexeddb

解决方案


创建一个异步方法,以便在openDatabase()添加值之前等待数据库打开。您可以通过使用使其异步.then(function() {

ngOnInit() {
    let  db = new NgxIndexedDB('DVdb', 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: 'Sumit', email: 'Sumit@test.com' }).then(
          () => {
              // Do something after the value was added
          },
          error => {
              console.log(error);
          }
        );
    });
}

推荐阅读