Applications typically have one single Dexie instance declared as its own module. This is where you declare which tables you need and how each table shall be indexed. A Dexie instance is a singleton throughout the application - you do not need to create it on demand. Export the resulting db instance from your module so that you can use it from your services to write or query data.
To make the best Typescript experience with Dexie.js, table properties (such as db.todoLists and db.todoItems) needs to be explicitly declared on a subclass of Dexie just to help out with the typings for your db instance, its tables and entity models.
// db.tsimportDexie,{Table}from'dexie';exportinterfaceTodoList{id?:number;title:string;}exportinterfaceTodoItem{id?:number;todoListId:number;title:string;done?:boolean;}exportclassAppDBextendsDexie{ todoItems!:Table<TodoItem,number>; todoLists!:Table<TodoList,number>;constructor(){super('ngdexieliveQuery');this.version(3).stores({ todoLists:'++id', todoItems:'++id, todoListId',});this.on('populate',()=>this.populate());}asyncpopulate(){consttodoListId=awaitdb.todoLists.add({ title:'To Do Today',});awaitdb.todoItems.bulkAdd([{ todoListId, title:'Feed the birds',},{ todoListId, title:'Watch a movie',},{ todoListId, title:'Have some sleep',}, ]);}}exportconstdb=newAppDB();
4. Turn App into an Offline ToDo app
In this sample we will use two components that builds up our ToDo application. For simplicity, we are letting our components talk directly to the db here. In a real application you might prefer to put the database action and queries via services.