How to create a firebase project and write to multiple real-time firebase databases in Angular?

Vikas Kohli
3 min readJun 19, 2021

In this, I will discuss how you can set up the firebase and write to multiple realtime firebase databases.

Firstly you need to set up a firebase project, go to firebase console https://console.firebase.google.com/u/0/ and create a project

Create Firebase Project
Project Steps

After creating the project, we need to add an app. We’re implementing in Angular so we will choose web as an option which is 3rd in the below diagram.

Choose Platform

After selecting the web app, they will provide the configuration which we need to include in the index file

Firebase configuration

If we using a normal website using HTML and js, then include the same in the index.html file. But we’re implementing this is ANgular so will include the script file in the index.html but the firebaseConfig we stored in the environment file.

Firstly install @angular/fire from npm.

In the app.module.ts, we import and then initialize the app in the @NgModule imports section

import { AngularFireModule } from '@angular/fire/';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AngularFireModule.initializeApp(environment.firebase) -> this is initalization],
providers: [],
bootstrap: [AppComponent]
})

Now create a service to write data in firebase

In the firebase.db.service.ts firstly I import the AngularFireDatabase and create a reference in the constructor then used to get and write data.

import { AngularFireDatabase } from '@angular/fire/database';

@Injectable()
export class FirebaseDbService {
constructor(
private db: AngularFireDatabase
){ }
getData(){
return this.db.database.ref("/my-node").once('value');
}
writeData(mydata: any){
this.db.database.ref(`/my-node`).update(data);
}
}

Here my-node can be any string like I used in the firebase database. I used it once so it means it called only when I called the function.

For multiple, firsts we need to store all URLs in the environment config file

export const environment = {
...here firebase config json,
allDbUrls: ["db1url","db2url","db3url",.... and so on]
}

In the firebase DB service file, we import the environment first.

import { environment } from '../../../environments/environment';getData(){
return this.db.database.app.database(`${environment.dbUrls[0]}`).ref("/my-node").once('value');
}
updateInMultiple(myNode: string, data: any){
for(let k=0;k<environment.dbUrls.length;k++){ this.db.database.app.database(`${environment.dbUrls[k]}`).ref(`/${myNode}`).update(data);
}
}

In the get data, I fetched data from DB URL which is in 0th position but when I write data, I m writing in all DBS.

So using this.db.database.app.database(${dburl}) we can write and listen to any specific database.

Happy Coding with Angular and Real time Firebase Database

--

--

Vikas Kohli

B.E Software Developer, Enthusiastic, Ego-surfing