访问同一Firebase应用程序项目的多个实时数据库 [英] Access multiple Realtime Databases of the same firebase app project
问题描述
我发现了一些说明,它们涉及到使用angularfire2将来自不同应用程序项目的多个数据库连接起来.但是我想访问同一项目中的数据库.
I found some explanations about connecting multiple databases from separate app projects with angularfire2. But I would like to access databases within the same project.
文档说:
// Get the default database instance for an app
var database = firebase.database();
// Get a secondary database instance by URL
var database = firebase.database('https://testapp-1234.firebaseio.com');
如何使用angularfire2做到这一点?
How can I do this with angularfire2?
推荐答案
I know you got a working answer here : https://github.com/angular/angularfire2/issues/1567
经过测试:"angularfire2":"^ 5.0.0-rc.6.0","firebase":"^ 4.12.1"
tested with : "angularfire2": "^5.0.0-rc.6.0", "firebase": "^4.12.1"
我已经建立了一个极简主义的包装,灵感来自我想分享的#1567.有两种方法使用不同的项目或相同的项目来使用多个数据库.
I've built a minimalist wrapper inspired of the #1567 I'd like to share. There are 2 methods with different or same project to use multiple databases.
您可能会使用第一个数据库,我不太理解在多个项目中使用多个数据库的意义.
You'll probably use the first one, I don't really understand the point of using multiple databases within multiple project.
@Injectable()
export class AngularFireWrapper {
// Default database
private _firebaseDb = this.afDb.database;
constructor(private afDb: AngularFireDatabase,
@Optional() dbName: string) {
console.log('Hello AngularFireWrapper, db :', dbName || 'default');
// 1st Method, same project, same auth
// environment.dbUrls = {
// ...
// otherDb: 'https://DB_NAME_SAME_PROJECT.firebaseio.com/'
// }
if (dbName && environment.dbUrls[dbName]) {
const app: any = this.afDb.app;
this._firebaseDb = app.database(environment.dbUrls[dbName]);
}
// 2nd Method, other project, different auth =/
// environment.dbConfigs = {
// ...
// otherDb: {...} // usual firebase configs
// }
if (dbName && environment.dbConfigs[dbName]) {
this._firebaseDb = firebase.initializeApp(environment.dbConfigs[dbName], dbName)
.database();
}
}
db(dbName): AngularFireWrapper {
return new AngularFireWrapper(this.afDb, dbName);
}
object(path: string): AngularFireObject<any> {
const ref = this._firebaseDb.ref(path);
return this.afDb.object(ref);
}
list(path: string, queryFn?: QueryFn): AngularFireList<any> {
const ref = this._firebaseDb.ref(path);
return this.afDb.list(ref, queryFn);
}
}
复制粘贴,像平常一样使用自定义服务注入它,然后:
Copy-Paste, inject it as you usually do with your custom services and then :
export class MyApp {
constructor(private afW: AngularFireWrapper) {
this.afW.object('test')
.valueChanges()
.subscribe(console.log)
// => output default db values
this.afW.db('otherDb').object('test')
.valueChanges()
.subscribe(console.log)
// => output otherDb values
}
这篇关于访问同一Firebase应用程序项目的多个实时数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!