-
Hello everyone. I'm trying to set up RxDB in an Angular application (v17), and I thought it would be a good idea to use the database as an injection token with ngxtension. I'm facing some problems. This is my setup: let DB_INSTANCE: RxDatabase;
// This is run via APP_INITIALIZER
export function initDatabase() {
_createDatabase().then(db => {
DB_INSTANCE = db;
});
}
export const [injectDatabase] = createInjectionToken(() => {
return DB_INSTANCE;
}); As you can see here. I create the RxDB database in an APP_INITIALIZER function and then use an injectionToken to return the database instance. Problem is that the token always returns app.component.ts @Component({ ... })
export class AppComponent {
private database = injectDatabase();
constructor() {
console.log(this.database) // returns undefined
}
} I've tried doing the same with a regular service and it works: @Injectable({ providedIn: 'root' })
export class DatabaseService {
get db(): RxDatabase {
return DB_INSTANCE;
}
}
@Component({ ... })
export class AppComponent {
private database = injectDatabase();
private databaseService = inject(DatabaseService);
constructor() {
console.log(this.database) // returns undefined
console.log(this.databaseService.db) // returns the instance
}
} Is this a wrong usage of injectionToken? Do they only work if their returned value is already set or is a contant? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There are some subtle differences between your
You can try returning a function that returns export const [injectDatabase] = createInjectionToken(() => {
return () => DB_INSTANCE;
});
@Component({ ... })
export class AppComponent {
private database = injectDatabase();
constructor() {
console.log(this.database()); // this would return the instance
}
} |
Beta Was this translation helpful? Give feedback.
There are some subtle differences between your
createInjectionToken
code and theDatabaseService
code.createInjectionToken
is only INVOKED ONCE and theDB_INSTANCE
isundefined
initially.get db()
which technically tries to get the latest reference toDB_INSTANCE
wheneverdatabaseService.db
is accessed.You can try returning a function that returns
DB_INSTANCE
withcreateInjectionToken
instead