Reputation: 458
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.
The documentation stated:
// 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');
How can I do this with angularfire2?
Upvotes: 1
Views: 1470
Reputation: 685
I know you got a working answer here : https://github.com/angular/angularfire2/issues/1567
tested with : "angularfire2": "^5.0.0-rc.6.0", "firebase": "^4.12.1"
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
}
Upvotes: 3