Prerequisites
Installed Node version of: v20.10.0.
Installing Angular Cli
You can see the official documentation for a better explanation.
- Open command prompt and run command below:
npm install -g @angular/cli
Create new Angular project
- Open a command prompt from a dedicated directory to store your Angular project.
- Run this command:
ng new angular-with-firebase // you can change angular-with-firebase with anything else
- You will be asked to configuring few things. For stysheet format, I choose CSS. Then hit enter.
- I don't know much about this so I choose no by typing
N
, then hit enter. - Your project now is being created.
- Once it done, open command prompt from inside your project and run
ng serve
to see our new project. By default, we will have it run athttp://localhost:4200/
.
Connecting Firebase with Angular
Configuring Firebase environment
- Open your project dashboard on Firebase Console.
- Click at settings icon near the
Project Overview
that you can find at upper left corner. - Choose
Project settings
. - Scroll down to your apps section. You will see a code snippet, the same one as when we first create the project. I choose
npm
because I will be usingnpm
. - Back to our Angular project directory, open command prompt. Let's install Firebase by running:
npm install firebase
- Once Firebase package installed, open our project in a code editor. I'm using Visual Studio Code.
-
In
src
directory, create new directory calledenvironments
. Inside this new directory, create a new file calledenvironment.ts
. This is what is going to be inside that file:export const environment = { production: false, firebaseConfig: { // to cut the chase, just copy it the snippet on step 3 apiKey: "abcdefghijklmnopqrstuvwxyz", authDomain: "domain-firebase.firebaseapp.com", projectId: "project-id", storageBucket: "storage-bucket", messagingSenderId: "1234567890", appId: "acnqw3nry23ibcadmqomxue38e23e28x29m", measurementId: "G-6GG2Q2LX8S", // You are not yet have this vapidKey: "" } }
To have your
vapidKey
, go back to your Firebase Project settings.Scroll until you see
Web configuration
section. ClickGenerate key pair
button.
-
Let's get back to step 7. Paste your key to
vapidKey
field.export const environment = { production: false, firebaseConfig: { apiKey: "abcdefghijklmnopqrstuvwxyz", authDomain: "domain-firebase.firebaseapp.com", projectId: "project-id", storageBucket: "storage-bucket", messagingSenderId: "1234567890", appId: "acnqw3nry23ibcadmqomxue38e23e28x29m", measurementId: "G-6GG2Q2LX8S", vapidKey: "BIddLYYlBZA1mijjbsG5ixKrvNgCqmy2H-qgI-PXSn84danwe7dtJOXjs9IDhNo_nQK0QzRKA96ocW8SDbKk5nRU" } }
-
Now, back to
src
directory, create new directory calledconfigs
. Inside that directory, create a new file calledfirebase.config.ts
. This is the content of the newly created file:import firebase from 'firebase/compat/app'; import { environment } from "../environments/environment"; import 'firebase/compat/messaging'; firebase.initializeApp(environment.firebaseConfig); export const messaging = firebase.messaging();
Working with service workers
- To work with service worker we going to need new dependency, so open a command prompt from your project directory and run:
npm install @angular/service-worker
- Go to Firebase Project Settings.
- Go to Firebase Cloud Messaging API (V1), there you will see a table containing your Sender ID. Copy the Sender ID.
- Back to our code editor, in
src
directory, create a file calledmanifest.json
. Paste your Sender ID here.{ "gcm_sender_id": "YOUR_SENDER_ID" }
- Open
index.html
at the same directory, in head tag, add:<link rel="manifest" href="./manifest.json">
-
Still in
src
directory, create a file calledfirebase-messaging-sw.js
.importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-app-compat.js"); importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging-compat.js"); const firebaseConfig = { // to cut the chase, just copy it from your Firebase Project settings apiKey: "abcdefghijklmnopqrstuvwxyz", authDomain: "domain-firebase.firebaseapp.com", projectId: "project-id", storageBucket: "storage-bucket", messagingSenderId: "1234567890", appId: "acnqw3nry23ibcadmqomxue38e23e28x29m", measurementId: "G-6GG2Q2LX8S", }; const app = firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging();
-
Go to project root directory, and find
angular.json
. Add this line inassets
:"src/manifest.json", "src/firebase-messaging-sw.js"
-
Back to command prompt, run:
ng build
Creating new Angular Component
- Open command prompt from your Angular project directory. Run this command:
ng generate component notification --inline-template
- Once it's done, you will see new directory inside
src/app
callednotification
. - Now, with your code editor, open
notification.component.ts
. -
Now, let's cook something from here. To check if we already correctly configure anything, I add some simple function. Now, my
notification.component.ts
looks like:import { Component, OnInit } from '@angular/core'; import { messaging } from '../../configs/firebase.config'; import { environment } from '../../environments/environment'; @Component({ selector: 'app-notification', standalone: true, imports: [], template: ` <p> notification works! </p> `, styleUrl: './notification.component.css' }) export class NotificationComponent implements OnInit { ngOnInit(): void { this.requestPermission(); this.listen(); } requestPermission() { messaging.getToken({vapidKey: environment.firebaseConfig.vapidKey}) .then((currentToken) => { if (currentToken) { console.log(currentToken); } else { console.log('No registration token available. Request permission to generate one.'); } }).catch((err) => { console.log(err); }); } listen() { messaging.onMessage((incomingMessage) => { console.log(incomingMessage); }) } }
-
Now, open
app.component.ts
which you can find atsrc\app\app.config.ts
. AddNotificationComponent
atimports
section.import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; import { NotificationComponent } from './notification/notification.component'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet, NotificationComponent], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = 'angular-with-firebase'; }
Open
app.component.html
atsrc\app\app.component.html
. At the end of lastdiv
close tag, add<app-notification></app-notification>
-
Create a new file called
app.module.ts
at the same level directory asapp.component.ts
andapp.component.html
(here's the relative path:src\app\app.module.ts
). Here's how I defined it:import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { NotificationComponent } from "./notification/notification.component"; import { messaging } from "../configs/firebase.config"; @NgModule({ declarations: [], imports: [ BrowserModule, NotificationComponent ], providers: [ { provide: 'messaging', useValue: messaging} ], bootstrap: [] }) export class AppModule {}
-
Now let's try running our application. In your project command prompt, run:
ng serve
Open our application at
http://localhost:4200/
.You will be asked for notification permission. Allow it.
Now open your browser console by inspecting element. You will see your token in there. It means we already configured our application!
Checking push notification functionality
- Make sure you are still running your Angular project.
- Go to Firebase Project Settings.
- Go to
Cloud Messaging
tab. - You will see this section.
- In Cloud Messaging API (Legacy) which still disabled, click the kebab menu (the three dots).
- Choose
Manage API in Google Cloud Console
. - You will be redirected to a new tab. Click
Enable
button. - Back to Firebase Project settings tab. Refresh it. You will see a new generated Server key by default.
- Now open Postman. Create new
POST
request. The endpoint ishttps://fcm.googleapis.com/fcm/send
. - Go to Headers tab.
- Add
Authorization
as key and the value iskey=your_server_key
. Server key is something that you got from step 8. - Add another headers of
Content-Type
and chooseapplication/json
- Go to Body tab. Choose
Raw
andJSON
then copy this:{ "notification": { "title": "New Notification", "body": "This is a sample push notification." }, "to": "insert token from Angular project console" }
- Click
Send
- In Postman, you will see this kind of response:
- In your Angular project console, you will see a notification coming in at the console:
Top comments (1)
is there a way to handle all this inside a service. Like creating an service named FcmService and handling the token generation and delete of token in that service