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
版权声明:本文标题:javascript - Angular how to init RxDB in provideAppInitializer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736308965a1933848.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论