Configuring Firebase with Angular standalone component
edisne
Posted on February 28, 2024
Being that by default (using Angular 17 ✨), generating a component using CLI, we get a standalone component and lack of updated documentation from Firebase I decided to publish my implementation of, in this case, a Real-time database connection.
First of, in my main.ts
I initialized the app and analytics
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
import { initializeApp } from 'firebase/app';
import { firebaseConfig } from '../src/app/environments/environment';
import { getAnalytics } from 'firebase/analytics';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
Then in my environment.ts I added firebaseConfig (That you get after creating a Web App on Firebase Console)
export const firebaseConfig = {
apiKey: 'XXXXXXXXXXXXXXXXXXXX',
authDomain: 'XXXXXXXXXXXXXXXXXXXX',
projectId: 'XXXXXXXXXXXXXXXXXXXX',
databaseURL:
'XXXXXXXXXXXXXXXXXXXX',
storageBucket: 'XXXXXXXXXXXXXXXXXXXX',
messagingSenderId: 'XXXXXXXXXXXXXXXXXXXX',
appId: 'XXXXXXXXXXXXXXXXXXXX',
measurementId: 'XXXXXXXXXXXXXXXXXXXX',
};
And it's pretty much ready to use, with no extra modules import and configuration. In your Component you first import:
import { getDatabase, ref, set } from 'firebase/database';
Then instantiate the database with:
databaseInstance = getDatabase();
and mutate data like so:
saveData(data) {
set(ref(this.databaseInstance, `/collection`), {
date: new Date().toISOString(),
...data,
})
.then(() => {
this.isSuccess = true;
})
.catch((error) => {
this.isError = true;
console.log('Failed to save data: ', error);
});
}
And that's it, hopefully, it saves someone at least a few minutes of frustration when configuring Firebase with standalone components. If I said something wrong, or you have some extra questions, feel free to write in comments. Cheers🍻
Posted on February 28, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.