admin管理员组

文章数量:1122826

I'm a ReactJS developer I decided to enhance my knowledge in Web Development in general it led me into diping my toe in water and trying Angular by developing an application that relies on RxDB.

I'm trying to make RxDB database accessible globally first thing I did is wrapping RxDB database inside an Angular service:

import { Injectable } from '@angular/core';
import { createRxDatabase, RxDatabase } from 'rxdb';
import { ItemCollection, itemSchema } from '../items/items.schema';
import { getRxStorageMemory } from 'rxdb/plugins/storage-memory';

type MyDatabaseCollections = {
  items: ItemCollection;
};
type MyDatabase = RxDatabase<MyDatabaseCollections>;

@Injectable({
  providedIn: 'root',
})
export class DatabaseService {
  private static database: MyDatabase;

  constructor() {}

  async initDatabase(): Promise<void> {
    if (!DatabaseService.database) {
      const db = await createRxDatabase<MyDatabaseCollections>({
        name: 'mydb',
        storage: getRxStorageMemory(),
      });

      await db.addCollections({
        items: {
          schema: itemSchema,
        },
      });

      DatabaseService.database = db;
    }
  }

  getDatabase(): MyDatabase {
    if (!DatabaseService.database) {
      throw new Error('Database not initialized yet');
    }
    return DatabaseService.database;
  }
}

and inside the root app app.config.ts is where the initializing of the service happens:

  providers: [
    DatabaseService,
    provideAppInitializer(() => inject(DatabaseService).initDatabase()),
  ],

Finally inside itemsponent.ts which is where I'm accessing the data the earliest:

@Component({
  selector: 'app-items',
  imports: [ToastModule],
  templateUrl: './itemsponent.html',
})
export class ItemsComponent {
  items: ItemType[] = [];

  constructor(
    private toastService: ToastService,
    private databaseService: DatabaseService,
  ) {
    this.getItems();
  }

  getItems() {
    const db = this.databaseService.getDatabase();
    const items = db.items.find().$;

    items.subscribe((docs) => {
      console.log(docs);
    });
  }

Is returning an error:

Database not initialized yet

本文标签: javascriptAngular how to init RxDB in provideAppInitializerStack Overflow