【问题标题】:Dexiedb Put method not working when adding primary key as argument添加主键作为参数时,Dexiedb Put 方法不起作用
【发布时间】:2019-11-26 23:31:11
【问题描述】:

我在我的 Angular 项目中使用 dexiedb。我有一个带有 cmets 表的数据库。我想将用户输入添加到数据库中,我正在使用 table.put(item, [key])。我只想在第一行添加,所以主键 = 0,这就是我指定键的原因。但它不起作用。

下面是我的代码 sn-p。将主键作为参数时出现错误。

在 'IDBObjectStore' 上执行 'put' 失败:提供了 o... 内联键和 key 参数。",

@Injectable()
export class DexieService{

    onNewComment = new EventEmitter<Comments>();

    contactDB: Dexie;

    constructor(){
        this.contactDB = new Dexie('contact');
        this.contactDB.version(1).stores({
            comments:'++id,comment'
        })
    }

addComment(comment: Comments): Promise<any>{   
            return(
                this.contactDB.table('comments').put(comment,0)
                   .then((result) =>{ 
                       this.onNewComment.next(comment);
                       return (result);
                   })
               )            
    }

预期的结果应该是,当添加任何新的 cmets 时,由于主键已经存在,它总是会转到主键 = 0 的第一行

【问题讨论】:

    标签: dexie


    【解决方案1】:

    您的主键(++id)是inbound,这意味着您只能在对象本身内指定键,不需要使用可选的键参数。如果使用可选的 key 参数,API 将失败,除非主键是出站的。此 API 反映了原始 IndexedDB 的 IDBObjectStore.put() 方法,该方法对入站键的工作方式相同。

    改为:

    this.contactDB.table('comments').put({...comment, id: 0})
    

    【讨论】:

    • 谢谢,这行得通。以前我试过你的代码没有花括号 {} 并且无法工作 this.contactDB.table('cmets').put(comment, id: 0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 2014-05-27
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多