Creation of an indexed database with Dexie was unsuccessful

I am currently working on an Angular application where I am encountering an issue with creating an indexed database. The database is not being created as expected.

Below is a snippet of the code responsible for inserting entries into the database:

  createImageFromBlob(ficname:any , image: Blob) {
    let reader = new FileReader();
    reader.addEventListener("load", (evt) => {
      let res = evt.target.result;

      // Store data URL in localStorage
      try {
        if (typeof res === "string") {
          localStorage.setItem(ficname, res);
          this.dixieDbService.addNewImage(ficname, res).then(r => console.log("inserted successfully"));
        }
      }
      catch (e) {
        console.log("Storage failed: " + e);
      }
    }, false);
    if (image) {
      reader.readAsDataURL(image);
    }
  }

Here is part of the bd.ts file:

import Table = Dexie.Table;
import Dexie from "dexie";

export interface ImageList {
  id?: number;
  imgName: string;
  imgDataUrlValue: string|ArrayBuffer;
}

export class AppDB extends Dexie {
  imageList!: Table<ImageList, number>;

  constructor() {
    super('ngdexieliveQuery');
    this.version(3).stores({
      imageList: '++id'
    });
   // this.on('populate', () => this.populate());
  }  
}

export const db = new AppDB();

And here is the service class:

import {Injectable} from "@angular/core";
import {liveQuery} from "dexie";
import {db, ImageList} from "../dixie/db";

@Injectable()
export class DixieIndexedDbService {
  imageList$ = liveQuery(() => db.imageList.toArray());
  listName = 'My local image list';

  async addNewImage(imgName:string, imgDataVal:any) {
    await db.imageList.add({
      imgName: imgName,
      imgDataUrlValue:imgDataVal
    });
  }

  async getImgDataValue(imgName:string) {
    return db.imageList.get({imgName: imgName});
  }
}

You can check out the sample working code on StackBlitz here:

https://stackblitz.com/edit/angular-ivy-znzhv8

Answer №1

When the constructor of Dexie is invoked without any options, the database will be created in the following ways:

  1. You can issue a call to open
  2. Alternatively, you can execute a query to the database. In the scenario mentioned above(OP), within the function createImageFromBlob, the load event handler should have been triggered, leading to the invocation of a method from DexieService which would then perform a database query based on the specified implementation. This sequence should result in the creation of the database.

The AppDB class includes a call to open...

import Table = Dexie.Table;
import Dexie from "dexie";

export interface ImageList {
  id?: number;
  imgName: string;
  imgDataUrlValue: string|ArrayBuffer;
}


export class AppDB extends Dexie {
  imageList!: Table<ImageList, number>;


  constructor() {
    super('ngdexieliveQuery');
    this.version(3).stores({
      imageList: '++id'
    });
    this.open(); // <---- Missing in OP
   // this.on('populate', () => this.populate());
  }
  
}

export const db = new AppDB();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Unable to modify the 'cflags' property of object '#<Object>' in Angular CLI and node-gyp

@angular/cli has a dependency on node-gyp, which is evident from the following: npm ls node-gyp <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16776666653b7477757d7970707f7573562738263826">[email protected]</a> /h ...

Guide on integrating Highcharts 3D into an Angular 5 application

Currently, I am making modifications to the app.module.ts file. import { ChartModule } from 'angular-highcharts'; I have also included the import: ChartModule Now I am interested in incorporating highchart-3d functionality. How can I achieve ...

Angular 4 RXJS Observable .interval() Fails to Execute in the Background

I have implemented a basic timer observable in my application that works fine. However, I noticed that when the tab is not active, the timer stops until I switch back to it. public timer = Observable .interval(100) Is there a way to keep the observable ...

What's the best way to fix a div to the bottom left corner of the screen?

I have explored various solutions regarding this issue, but none of them seem to meet my specific requirements. What I am trying to achieve is the correct positioning of a div as depicted in the green area in the image. https://i.sstatic.net/O9OMi.png Th ...

Angular tests are not reflecting HTML changes when there is a modification in the injected service

I'm currently testing a component that dynamically displays a button based on the user's login status. The user details are obtained from a service method, and the component uses a getter to access this information. Inside the component: get me ...

Issue: The Karma plugin in Angular CLI >6.0 is now exported from "@angular-devkit/build-angular" instead

Issue: I'm encountering an error in Angular CLI version 6.0 or higher where the Karma plugin is now exported by "@angular-devkit/build-angular". // Below is the Karma configuration file, you can find more information at // module.exports = function ...

Fixing the 401 (Unauthorized) error when attempting to log in

I keep encountering a 401 error when trying to log in with JWT authentication. Strangely, the signup page works perfectly fine and successfully adds the user to the database. However, for some reason, the login functionality is not working. I'm unsure ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Converted requests from loopback to angular2 resulted in an error message, as the script's MIME type ('text/html') was determined to be non-executable

Currently, I have set up loopback as the backend API and angular2 as the frontend for my project. Loopback is serving my angular2 frontend without any issues. However, whenever I refresh a page, loopback seems to struggle with handling the URL because tha ...

Trying to enter the function, but it exits without executing

I'm facing an issue with my function that involves making multiple calls to an observer. I need the function to wait until all the calls are complete before returning. I attempted putting the return statement inside the subscribe method, but it result ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

Adding an attribute to the last item of an Angular / NGX Bootstrap component

I am working with a dynamic list that utilizes NGX Bootstrap Dropdowns to showcase 4 sets of dropdown lists. However, the Dropdowns in the final list are getting obscured off-page. Thankfully, NGX Bootstrap offers a solution in the form of a dropUp option ...

Improve Observable to prevent type assertion errors

Currently working on writing unit tests for a CanDeactive Guard, encountering a type assertion error in my jasmine spec: // Mock Guard defined at the top of the spec file class MockGuardComponent implements ComponentCanDeactivate { // Adjust this value t ...

Certain information is failing to be added to the list

userSPMSnapshot.forEach((doc) => { console.log(doc.id, "=>", doc.data()); userSPMList.push(userSPM.fromFirestore(doc)); }); console.log(userSPMList) I'm encountering an issue where some fields in my data lose their values when I p ...

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

What is preventing typescript from inferring these linked types automatically?

Consider the following code snippet: const foo = (flag: boolean) => { if (flag) { return { success: true, data: { name: "John", age: 40 } } } return { success: false, data: null } ...

Verifying user privilege within settings database (written in Typescript for Aurelia framework)

Working on navigation with authorization. This is a snippet of my code: run(navigationInstruction: NavigationInstruction, next: Next) : Promise<any> { let requiredRoles = navigationInstruction.getAllInstructions() .map(i ...

Regex for US zip code with an optional format

Searching for a regular expression to validate US zip codes. I have come across multiple examples, but none of them cater to the scenario where the zip code is optional. The input field I am working on does not require a zip code, so it should accept a 5 ...

Globalizing Your Angular 4 Application

Looking for a way to enable Internationalization (i18n) on button click in Angular 4 with support for at least four languages? I attempted to use the Plunker example provided here, but it seems to be encountering issues: ...

Creating a dynamic form with Angular 7 using ngFor and ngModel, incorporating validation through ngFrom attribute

I am currently working on developing an Angular input form that resembles a table. Here is my current approach: HTML: <form (ngSubmit)="doSomething()"> <table> <thead> <tr>First Name</tr> <tr>Last ...