Angular Init two services that depends on each other

Discussão em 'Angular' iniciado por Kadiem Alqazzaz, Dezembro 2, 2024.

  1. I have Database service that reads data from IndexedDB using RxDB library and has initDatabase function to initialize it.

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

    constructor() {}

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

    await db.addCollections({
    items: {
    schema: itemSchema,
    },
    baseUnits: {
    schema: baseUnitSchema,
    },
    brands: {
    schema: brandSchema,
    },
    contacts: {
    schema: contactSchema,
    },
    suppliers: {
    schema: SupplierSchema,
    },
    });

    DatabaseService.database = db;
    }
    }

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


    And Items service that depends on the Database service by initItemsService function

    @Injectable({
    providedIn: 'root',
    })
    export class ItemsService {
    private itemsSubject = new BehaviorSubject<ItemType[]>([]);
    private itemSearchTermSubject = new BehaviorSubject<string>('');

    public items$;
    public searchTerm$;

    constructor(private databaseService: DatabaseService) {
    this.items$ = this.itemsSubject.asObservable();
    this.searchTerm$ = this.itemSearchTermSubject.asObservable();
    }

    setItems(items: ItemType[]) {
    this.itemsSubject.next(items);
    }

    getItems(): ItemType[] {
    return this.itemsSubject.getValue();
    }

    setItemSearchTerm(term: string) {
    this.itemSearchTermSubject.next(term);
    }

    getItemSearchTerm(): string {
    return this.itemSearchTermSubject.getValue();
    }

    findItemsByName(name: string): ItemType[] {
    return this.itemsSubject
    .getValue()
    .filter((item) => item.name.toLowerCase().includes(name.toLowerCase()));
    }

    initItemsService() {
    this.databaseService
    .getDatabase()
    .items.find()
    .$.subscribe((docs) => {
    this.setItems(docs);
    });
    }
    }


    Finally initializing both services inside app.config.ts

    export const appConfig: ApplicationConfig = {
    providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAnimations(),
    MessageService,
    DatabaseService,
    provideAppInitializer(() => inject(DatabaseService).initDatabase()),
    provideAppInitializer(() => inject(ItemsService).initItemsService()),
    ],
    };


    But the database is not yet initialized by the time Item reads it getting error:


    Database not initialized yet
    ​

    Which is the error in funcrion getDatabase()

    Continue reading...

Compartilhe esta Página