Fireship · @fireship
Send Push Notifications in Angular with Firebase Cloud Messaging
Uploaded August 4, 2017 · Length 5:39
Summary
Send push notifications in Angular using Firebase Cloud Messaging with a service worker and cloud function.
- firebase cloud messaging
- angular push notifications
- service worker
- cloud function
- firebase cloud functions
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
Firebase Cloud Messaging allows you to
- 0:02
send push notifications throughout
- 0:04
multiple devices even after an app's
- 0:06
been closed. It does this on the web by
- 0:08
registering a service worker that
- 0:10
listens for messages from Firebase in
- 0:12
the background. As you can see here,
- 0:13
we've completely closed our Angular app
- 0:15
in the browser, but we still get this
- 0:17
push notification on our operating
- 0:19
system directly from Firebase. Many apps
- 0:22
do this to notify their users of
- 0:24
important information such as Slack,
- 0:26
which will notify users when they have a
- 0:28
new mention on a channel. Let's get
- 0:31
started by building this worker into our
- 0:32
Angular app. Create a new file in the
- 0:34
source directory called Cloud Messaging
- 0:37
SW.js.
- 0:38
Then inside that file, we'll import the
- 0:41
Firebase SDK and initialize it with only
- 0:44
the messaging sender ID. Then we set a
- 0:46
variable with the Firebase messaging
- 0:48
library. That's actually all we need to
- 0:50
do to set up the background worker.
- 0:52
Everything else will happen
- 0:53
automatically. However, to ensure
- 0:55
compatibility with modern browsers, we
- 0:57
need to add a manifest.json file. Inside
- 1:00
this file, we include the GCM sender ID,
- 1:04
which is the same for all applications.
- 1:05
So, keep it the same as it appears in
- 1:07
this video. And then you'll want to link
- 1:09
the manifest in the head of your
- 1:11
index.html file. To ensure these two
- 1:14
newly created files get included when we
- 1:16
build the app, we want to add them to
- 1:17
the Angular CLI.json file.
- 1:22
With the initial setup done, we can
- 1:24
start building the service. We're going
- 1:26
to need both the Angular Fire database
- 1:28
and Angular Fire O modules as well as
- 1:30
the Firebase SDK. We're going to keep
- 1:33
track of the most recent message with a
- 1:35
behavior subject, which is just an
- 1:37
observable that we can push new data to.
- 1:39
So the way cloud messaging works is the
- 1:41
browser will first ask the user for
- 1:43
permission for an app to send them cloud
- 1:46
messages and then Firebase will give us
- 1:47
a token once that permission has been
- 1:49
granted. What we need to do is save that
- 1:52
token with the user's O ID on the
- 1:54
Firebase database so we can use it on
- 1:56
the back end when we start sending
- 1:57
messages with Firebase Cloud Functions.


