Send Push Notifications in Angular with Firebase Cloud Messaging

Fireship · Beginner ·🛡️ AI Safety & Ethics ·8y ago

Key Takeaways

The video demonstrates how to send push notifications in Angular using Firebase Cloud Messaging, including setting up a service worker, requesting permission, and sending messages using Firebase Cloud Functions.

Full Transcript

Firebase Cloud Messaging allows you to send push notifications throughout multiple devices even after an app's been closed. It does this on the web by registering a service worker that listens for messages from Firebase in the background. As you can see here, we've completely closed our Angular app in the browser, but we still get this push notification on our operating system directly from Firebase. Many apps do this to notify their users of important information such as Slack, which will notify users when they have a new mention on a channel. Let's get started by building this worker into our Angular app. Create a new file in the source directory called Cloud Messaging SW.js. Then inside that file, we'll import the Firebase SDK and initialize it with only the messaging sender ID. Then we set a variable with the Firebase messaging library. That's actually all we need to do to set up the background worker. Everything else will happen automatically. However, to ensure compatibility with modern browsers, we need to add a manifest.json file. Inside this file, we include the GCM sender ID, which is the same for all applications. So, keep it the same as it appears in this video. And then you'll want to link the manifest in the head of your index.html file. To ensure these two newly created files get included when we build the app, we want to add them to the Angular CLI.json file. With the initial setup done, we can start building the service. We're going to need both the Angular Fire database and Angular Fire O modules as well as the Firebase SDK. We're going to keep track of the most recent message with a behavior subject, which is just an observable that we can push new data to. So the way cloud messaging works is the browser will first ask the user for permission for an app to send them cloud messages and then Firebase will give us a token once that permission has been granted. What we need to do is save that token with the user's O ID on the Firebase database so we can use it on the back end when we start sending messages with Firebase Cloud Functions. To do that, we will subscribe to the Angular Fire O state taking only one just to prevent a longunning subscription. Then we'll save the O ID as the key with the token as the value in a collection called FCM tokens in the database. The token will change anytime the user clears their browser cache. So it's important to update this token periodically. In this example, we're going to update the token every time this get permission function runs. This will happen whenever the browser asks the user for permission to send them notifications. The request permission function will trigger that popup that the user has to confirm and then from there we can get the token and update the token in the database. The last thing we need to do is listen for new messages and then we'll update that behavior subject whenever a new message is received. We do this by calling on message which will return the message from Firebase and then we can call next on our behavior subject and pass it that value. So now we can use these functions in the app component or any other component that you want to set up messaging with. When the user is actively using the app, we want to show the notification inside the app itself. We don't want it to come from some external source which would be distracting. So to do that, we inject the messaging service and first get permission and then we set up the receive message function and then set a variable on the component to that behavior subject. Again, a behavior subject is just an observable. So we can unwrap it in the template with the async pipe. So here we're handling the notification in Angular and it should look something like this. Notice the message appears directly in our Angular app and not coming from the external browser or operating system. If the app were closed at the time this message was sent, the service worker would take over and send the message to the external browser or operating system. Now that we know how to receive messages, we need a way to send them, which I'm going to do with a Firebase Cloud function. If you don't want to deploy a cloud function, check out the link in the description where I provide a curl command to send push messages over HTTP, but in most cases, you're going to be sending push notifications when something happens in your database. So, it's a perfect fit for Firebase Cloud Functions. In this example, we're going to create a function called FCM send, and it's going to run during the onreate trigger in the database. So, anytime new data is added to the messages for a given user, this function will run. So, we'll define a variable called payload, and that's the actual message that's going to be seen by the user. From there, we'll tap into the admin database and get the token for that user. So, we'll chain together a couple promises and then once we have the actual token, we can send that to the Firebase messaging library. We call send to device and send it the token as well as the payload or the message. This is what will actually trigger the message to be sent to that device. And that's pretty much it. Pretty simple cloud function. Go ahead and deploy the function and you should be ready to start sending messages to your users. As you can see here, we update some data on the messages node and the user is automatically updated with that push notification. If this video helped you, please like and subscribe. And if you're serious about Angular and Firebase, consider becoming a pro member at angular firebase.com where you'll get a free copy of my book, The Angular Firebase Survival Guide. Thanks for watching and I'll talk to you soon. [Applause] [Music]

Original Description

Learn how to send push notifications to users, even after they have closed an Angular app in the browser. Check out the full lesson code here: https://angularfirebase.com/lessons/send-push-notifications-in-angular-with-firebase-cloud-messaging Official Firebase Cloud Messaging (FCM) docs: https://firebase.google.com/docs/cloud-messaging/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Fireship · Fireship · 35 of 60

1 Angular 4 Development and Production Environments with Firebase
Angular 4 Development and Production Environments with Firebase
Fireship
2 OAuth with Angular and Firebase Tutorial
OAuth with Angular and Firebase Tutorial
Fireship
3 Anonymous Authentication with Angular and Firebase - Lazy Registration
Anonymous Authentication with Angular and Firebase - Lazy Registration
Fireship
4 Angular Router Guards for Firebase Users
Angular Router Guards for Firebase Users
Fireship
5 Angular Firebase CRUD App with NoSQL Database Tutorial
Angular Firebase CRUD App with NoSQL Database Tutorial
Fireship
6 Upload Files from Angular to Firebase Storage
Upload Files from Angular to Firebase Storage
Fireship
7 How to Deploy an Angular App to Firebase Hosting
How to Deploy an Angular App to Firebase Hosting
Fireship
8 Sharing Data between Components in Angular
Sharing Data between Components in Angular
Fireship
9 Loading Spinners for Asynchronous Firebase Data
Loading Spinners for Asynchronous Firebase Data
Fireship
10 Angular 4 Transactional Email with Google Firebase Cloud Functions
Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
11 Firebase Database Rules Tutorial
Firebase Database Rules Tutorial
Fireship
12 Autocomplete Search with Angular4 and Firebase
Autocomplete Search with Angular4 and Firebase
Fireship
13 Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Fireship
14 Angular Drag-and-Drop File Uploads to Firebase Storage
Angular Drag-and-Drop File Uploads to Firebase Storage
Fireship
15 Text Translation with Firebase Cloud Functions onWrite and Angular 4
Text Translation with Firebase Cloud Functions onWrite and Angular 4
Fireship
16 Custom Usernames with Firebase Authentication
Custom Usernames with Firebase Authentication
Fireship
17 Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Fireship
18 Simple Pagination with Firebase and Angular 4
Simple Pagination with Firebase and Angular 4
Fireship
19 How to Connect Firebase Users to their Data - 3 Methods
How to Connect Firebase Users to their Data - 3 Methods
Fireship
20 Add Toast Message Notifications to your Angular App
Add Toast Message Notifications to your Angular App
Fireship
21 Facebook-Inspired Reactions System with Angular and Firebase
Facebook-Inspired Reactions System with Angular and Firebase
Fireship
22 Learn NgModule in Angular with Examples
Learn NgModule in Angular with Examples
Fireship
23 Lazy Loading Components in Angular 4
Lazy Loading Components in Angular 4
Fireship
24 Stripe Checkout Payments with Angular and Firebase - Part 1
Stripe Checkout Payments with Angular and Firebase - Part 1
Fireship
25 Process Stripe Payments with Firebase Cloud Functions - Part 2
Process Stripe Payments with Firebase Cloud Functions - Part 2
Fireship
26 Selling Digital Content in Angular with Stripe Payments - Part 3
Selling Digital Content in Angular with Stripe Payments - Part 3
Fireship
27 Angular 4 Full Text Search with Algolia - Part 1
Angular 4 Full Text Search with Algolia - Part 1
Fireship
28 Algolia with Firebase Cloud Functions - Part 2
Algolia with Firebase Cloud Functions - Part 2
Fireship
29 Firebase Phone Authentication in Angular 4
Firebase Phone Authentication in Angular 4
Fireship
30 Top 7 RxJS Concepts for Angular Developers
Top 7 RxJS Concepts for Angular Developers
Fireship
31 Learn Angular Animations with 5 Examples
Learn Angular Animations with 5 Examples
Fireship
32 Advanced Firebase Data Filtering (Multi-Property)
Advanced Firebase Data Filtering (Multi-Property)
Fireship
33 Realtime Maps with Mapbox + Firebase + Angular
Realtime Maps with Mapbox + Firebase + Angular
Fireship
34 Angular Reactive Forms with Firebase Database Backend
Angular Reactive Forms with Firebase Database Backend
Fireship
Send Push Notifications in Angular with Firebase Cloud Messaging
Send Push Notifications in Angular with Firebase Cloud Messaging
Fireship
36 Top 7 Ways to Debug Angular 4 Apps
Top 7 Ways to Debug Angular 4 Apps
Fireship
37 Infinite Scroll with Angular and Firebase
Infinite Scroll with Angular and Firebase
Fireship
38 Use TypeScript with Firebase Cloud Functions
Use TypeScript with Firebase Cloud Functions
Fireship
39 Realtime Graphs and Charts with Plotly and Firebase
Realtime Graphs and Charts with Plotly and Firebase
Fireship
40 Role-Based User Permissions in Firebase
Role-Based User Permissions in Firebase
Fireship
41 User Presence System in Realtime - Online, Offline, Away
User Presence System in Realtime - Online, Offline, Away
Fireship
42 Location-based Queries with GeoFire and Angular Google Maps
Location-based Queries with GeoFire and Angular Google Maps
Fireship
43 Angular ngrx Redux Quick Start Tutorial
Angular ngrx Redux Quick Start Tutorial
Fireship
44 Angular Ngrx Effects with Firebase Database
Angular Ngrx Effects with Firebase Database
Fireship
45 Progressive Web Apps with Angular
Progressive Web Apps with Angular
Fireship
46 Angular Ngrx with Firebase Google OAuth User Authentication
Angular Ngrx with Firebase Google OAuth User Authentication
Fireship
47 RxJS Quick Start with Practical Examples
RxJS Quick Start with Practical Examples
Fireship
48 Send SMS Text Messages with Twilio and Firebase
Send SMS Text Messages with Twilio and Firebase
Fireship
49 Firebase Database Performance Profiling
Firebase Database Performance Profiling
Fireship
50 Native Desktop Apps with Angular and Electron
Native Desktop Apps with Angular and Electron
Fireship
51 Subscription Payments with Stripe, Angular, and Firebase
Subscription Payments with Stripe, Angular, and Firebase
Fireship
52 Firestore with AngularFire5 Quick Start Tutorial
Firestore with AngularFire5 Quick Start Tutorial
Fireship
53 Angular HTTP Client Quick Start Tutorial
Angular HTTP Client Quick Start Tutorial
Fireship
54 Google Sign-In with Firestore Custom User Data
Google Sign-In with Firestore Custom User Data
Fireship
55 Star Review System from Scratch with Firestore + Angular
Star Review System from Scratch with Firestore + Angular
Fireship
56 Angular Chatbot with Dialogflow (API.ai)
Angular Chatbot with Dialogflow (API.ai)
Fireship
57 Learn @ngrx/entity and Feature Modules
Learn @ngrx/entity and Feature Modules
Fireship
58 Infinite Scroll Pagination with Firestore
Infinite Scroll Pagination with Firestore
Fireship
59 Faster Firestore via Data Aggregation
Faster Firestore via Data Aggregation
Fireship
60 Contentful - CMS for Angular Progressive Web Apps
Contentful - CMS for Angular Progressive Web Apps
Fireship

Learn how to send push notifications in Angular using Firebase Cloud Messaging, including setting up a service worker and using Firebase Cloud Functions to send messages.

Key Takeaways
  1. Create a new file for the service worker
  2. Import the Firebase SDK and initialize it
  3. Add a manifest.json file for compatibility
  4. Link the manifest in the index.html file
  5. Add the service worker and manifest to the Angular CLI.json file
  6. Create a service to handle messaging
  7. Use a behavior subject to store the most recent message
  8. Request permission and save the token to the Firebase database
  9. Listen for new messages and update the behavior subject
  10. Use Firebase Cloud Functions to send messages
💡 Using a service worker and Firebase Cloud Messaging allows for push notifications to be sent even when the app is closed.

Related AI Lessons

AI Security Isn't a Product. It's an Engineering Discipline.
Learn why AI security requires a continuous engineering discipline rather than a one-time product implementation, and how to apply this mindset to your AI development workflow
Dev.to AI
Why Solving Legal AI's Context Problem Is Harder Than You Think
Solving legal AI's context problem requires understanding decision-making processes, not just having large models
Forbes Innovation
How Can We Truly Protect Information Privacy in the Age of Artificial Intelligence?
Learn how to prioritize information privacy in the age of AI and make it a competitive advantage
Medium · Machine Learning
The AI Validation Gap: The $2.5 Trillion Blind Spot In Enterprise AI
The AI validation gap poses a strategic risk to enterprises, costing $2.5 trillion, and requires immediate attention
Forbes Innovation
Up next
Containers Don't Make Your AI Agent Safe
Web Dev Simplified
Watch →