
To install Firebase in an Angular application, you need to follow these steps:
Create a new Angular project or use an existing one. You can create a new project using the Angular CLI by running the following command in your terminal:
ng new my-firebase-app
Go to the root directory of your project and install the Firebase dependencies by running the following command:
npm install firebase @angular/fire --save
This will install Firebase and AngularFire packages and save them to your package.json file.
Next, you need to import the Firebase and AngularFire modules in your Angular app module. Open the app.module.ts file and add the following imports at the top of the file:
import { NgModule } from '@angular/core';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { environment } from '../environments/environment';
@NgModule({
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule
],
// ...
})
export class AppModule { }
In the code above, we are importing the AngularFireModule and AngularFireAuthModule modules from @angular/fire. We are also initializing the Firebase app using the configuration settings stored in environment.firebase file. You can define these settings in your environment.ts and environment.prod.ts files.
export const environment = {
production: false,
firebase: {
apiKey: 'API_KEY',
authDomain: 'PROJECT_ID.firebaseapp.com',
databaseURL: 'https://PROJECT_ID.firebaseio.com',
projectId: 'PROJECT_ID',
storageBucket: 'PROJECT_ID.appspot.com',
messagingSenderId: 'SENDER_ID',
appId: 'APP_ID'
}
};
Once you have imported the modules and initialized the Firebase app, you can use the Firebase services in your Angular components and services. For example, to use the Firebase Authentication service, you can inject the AngularFireAuth service in your component or service and call its methods to authenticate users.
import { Component } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
@Component({
selector: 'app-login',
template: `<br /><div ngif="auth.user | async as user; else showLogin">
Welcome {{ user.email }}
<button click="logout()">Logout</button>
<br /></div>
<ng-template showlogin>
<button click="login()">Login with Google</button>
</ng-template>
`
})
export class LoginComponent {
constructor(public auth: AngularFireAuth) {}
login() {
this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}
logout() {
this.auth.signOut();
}
}
In the code above, we are using the AngularFireAuth service to authenticate users using Google sign-in provider. That's it! You have successfully installed Firebase in your Angular app and used its services to authenticate users.