Angular how to init RxDB in provideAppInitializer

Discussão em 'Angular' iniciado por Kadiem Alqazzaz, Novembro 21, 2024.

  1. 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 items.component.ts which is where I'm accessing the data the earliest:

    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
    ​

    Continue reading...

Compartilhe esta Página