Skip to content

Commit 78a9736

Browse files
davideastjamesdaniels
authored andcommitted
docs(*): Document AngularFireFunctions and AngularFireMessaging (#1856)
1 parent 91ec37e commit 78a9736

File tree

3 files changed

+277
-1
lines changed

3 files changed

+277
-1
lines changed

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,12 @@
1111
- **Realtime bindings** - Synchronize data in realtime.
1212
- **Authentication** - Log users in with a variety of providers and monitor authentication state in realtime.
1313
- **Offline Data** - Store data offline automatically with AngularFirestore.
14+
- **Server-side Render** - Generate static HTML to boost perceived performance or create static sites.
1415
- **ngrx friendly** - Integrate with ngrx using AngularFire's action based APIs.
16+
- **Manage binary data** - Upload, download, and delete binary files like images, videos, and other blobs.
17+
- **Call server code** - Directly call serverless Cloud Functions with user context automatically passed.
18+
- **Push notifications** - Register and listen for push notifications
19+
- **Modular** - Include only what's needed. No AngularFire package is above 3kb with most under 2kb (gzipped).
1520

1621
#### Quick links
1722
[Contributing](CONTRIBUTING.md)
@@ -90,8 +95,13 @@ Firebase offers two cloud-based, client-accessible database solutions that suppo
9095
### Universal
9196
- [Server-side Rendering with Universal](docs/server-side-rendering.md)
9297

93-
### Deploy to Firebase Hosting
98+
### Send push notifications
99+
- [Getting started with Firebase Messaging](docs/messaging/messaging.md)
100+
101+
### Directly call Cloud Functions
102+
- [Getting started with Callable Functions](docs/functions/functions.md)
94103

104+
### Deploy to Firebase Hosting
95105
- [Deploying AngularFire to Firebase Hosting](docs/deploying-angularfire-to-firebase.md)
96106

97107
### Ionic

docs/functions/functions.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# AngularFireFunctions
2+
3+
> The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app.
4+
5+
### Import the `NgModule`
6+
7+
Cloud Functions for AngularFire is contained in the `@angular/fire/functions` module namespace. Import the `AngularFireFunctionsModule` in your `NgModule`. This sets up the `AngularFireFunction` service for dependency injection.
8+
9+
```ts
10+
import { BrowserModule } from '@angular/platform-browser';
11+
import { NgModule } from '@angular/core';
12+
import { AppComponent } from './app.component';
13+
import { AngularFireModule } from '@angular/fire';
14+
import { AngularFireFunctionsModule } from '@angular/fire/functions';
15+
import { environment } from '../environments/environment';
16+
17+
@NgModule({
18+
imports: [
19+
BrowserModule,
20+
AngularFireModule.initializeApp(environment.firebase),
21+
AngularFireFunctionsModule
22+
],
23+
declarations: [ AppComponent ],
24+
bootstrap: [ AppComponent ]
25+
})
26+
export class AppModule {}
27+
```
28+
29+
### Injecting the AngularFireFunctions service
30+
31+
Once the `AngularFireFunctionsModule` is registered you can inject the `AngularFireFunctions` service.
32+
33+
```ts
34+
import { Component } from '@angular/core';
35+
import { AngularFireFunctions } from '@angular/fire/functions';
36+
37+
@Component({
38+
selector: 'app-component',
39+
template: ``
40+
})
41+
export class AppComponent {
42+
constructor(private fns: AngularFireFunctions) { }
43+
}
44+
```
45+
46+
### Creating a callable function
47+
48+
AngularFireFunctions is super easy. You create a function on the server side and then "call" it by its name with the client library.
49+
50+
| method | |
51+
| ---------|--------------------|
52+
| `httpCallable(name: string): (data: T) ` | Creates a callable function based on a function name. Returns a function that can create the observable of the http call. |
53+
```ts
54+
55+
import { Component } from '@angular/core';
56+
import { AngularFireStorage } from '@angular/fire/functions';
57+
58+
@Component({
59+
selector: 'app-root',
60+
template: `{ data$ | async }`
61+
})
62+
export class AppComponent {
63+
constructor(private fns: AngularFireFunctions) {
64+
const callable = fns.httpsCallable('my-fn-name');
65+
this.data$ = callable({ name: 'some-data' });
66+
}
67+
}
68+
```
69+
70+
Notice that calling `httpsCallable()` does not initiate the request. It creates a function, which when called creates an Observable, subscribe or convert it to a Promise to initiate the request.

docs/messaging/messaging.md

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
# AngularFireMessaging
2+
3+
> The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API.
4+
5+
### AngularFireMessaging is not compatible with the Angular Service Worker
6+
7+
If you are using the Angular Service Worker, you are not currently able to use AngularFireMessaging. If you'd like this feature please file an issue in [either repository](https://github.com/angular/angular/tree/master/packages/service-worker). Your alternatives are to use [WorkboxJS](https://developers.google.com/web/tools/workbox/) or just simply use the Firebase Messaging Service Worker, which is detailed below.
8+
9+
### Import the `NgModule`
10+
11+
Cloud Storage for AngularFire is contained in the `@angular/fire/messaging` module namespace. Import the `AngularFireMessagingModule` in your `NgModule`. This sets up the `AngularFireMessaging` service for dependency injection.
12+
13+
```ts
14+
import { BrowserModule } from '@angular/platform-browser';
15+
import { NgModule } from '@angular/core';
16+
import { AppComponent } from './app.component';
17+
import { AngularFireModule } from '@angular/fire';
18+
import { AngularFireStorageModule } from '@angular/fire/messaging';
19+
import { environment } from '../environments/environment';
20+
21+
@NgModule({
22+
imports: [
23+
BrowserModule,
24+
AngularFireModule.initializeApp(environment.firebase),
25+
AngularFireMessagingModule
26+
],
27+
declarations: [ AppComponent ],
28+
bootstrap: [ AppComponent ]
29+
})
30+
export class AppModule {}
31+
```
32+
33+
### Setting up the Firebase Messaging Service Worker
34+
35+
There are two parts Firebase Messaging, a Service Worker and the DOM API. AngularFireMessaging allows you to request permission, get tokens, delete tokens, and subscribe to messages on the DOM side. To register to receive notifications you need to set up the Service Worker. [The official Firebase documentation for setting up the details exactly how to do that](https://firebase.google.com/docs/cloud-messaging/js/client).
36+
37+
You can either use the `firebase-messaging-sw.js` file provided in the docs or you can set your own Service Worker to import that script. Make sure to set up your `.angular-cli.json` file to copy over the Service Worker file:
38+
39+
```json
40+
"assets": [
41+
"assets",
42+
"favicon.ico",
43+
"firebase-messaging-sw.js",
44+
"manifest.json"
45+
],
46+
```
47+
48+
### Requesting permission
49+
50+
Once you have the Firebase Messaging Service Worker setup and installed, you need to request permission to send a user notifications. While the browser will popup a UI for you, it is highly recommend to ask the user for permission with a custom UI and only ask when it makes sense. If you blindly ask for permission you have an extremely high chance of getting denied.
51+
52+
```ts
53+
import { Component } from '@angular/core';
54+
import { AngularFireMessaging } from '@angular/fire/messaging';
55+
56+
@Component({
57+
selector: 'app-root',
58+
template: `
59+
<button (click)="requestPermission()">
60+
Hey this is a chat app, you should let us send you notifications for these reasons!
61+
</button>
62+
`
63+
})
64+
export class AppComponent {
65+
constructor(private afMessaging: AngularFireMessaging) { }
66+
requestPermission() {
67+
this.afMessaging.requestPermission
68+
.subscribe(
69+
() => { console.log('Permission granted!'); },
70+
(error) => { console.error(error); },
71+
);
72+
}
73+
}
74+
```
75+
76+
Once you have the permission of the user, you need their token. You can do this with the `getToken` observable or the `tokenChanges` observable. The `tokenChanges` observable listens for token refreshes whereas the `getToken` observable is a one-time call.
77+
78+
```ts
79+
import { Component } from '@angular/core';
80+
import { AngularFireMessaging } from '@angular/fire/messaging';
81+
import { mergeMapTo } from 'rxjs/operators';
82+
83+
@Component({
84+
selector: 'app-root',
85+
template: `
86+
<button (click)="requestPermission()">
87+
Hey this is a chat app, you should let us send you notifications for these reasons!
88+
</button>
89+
`
90+
})
91+
export class AppComponent {
92+
constructor(private afMessaging: AngularFireMessaging) { }
93+
requestPermission() {
94+
this.afMessaging.requestPermission
95+
.pipe(mergeMapTo(this.afMessaging.tokenChanges))
96+
.subscribe(
97+
(token) => { console.log('Permission granted! Save to the server!', token); },
98+
(error) => { console.error(error); },
99+
);
100+
}
101+
}
102+
```
103+
104+
Once you have a user's token, you need to save it to the server in order to send them notifications in response to events. Let's say ou want to send a push each time a user sends a chat message. Once a user grants permission, you can send the token to the Realtime Database or Cloud Firestore and associate it with a unique id, like a Firebase Auth UID. You can then create a Cloud Function trigger that looks up the user's token when a chat message is created.
105+
106+
### Shortcutting token requests
107+
108+
An easier way of requesting permission and getting tokens is with the `requestToken` observable. It combines the two steps above into one observable.
109+
110+
```ts
111+
import { Component } from '@angular/core';
112+
import { AngularFireMessaging } from '@angular/fire/messaging';
113+
114+
@Component({
115+
selector: 'app-root',
116+
template: `
117+
<button (click)="requestPermission()">
118+
Hey this is a chat app, you should let us send you notifications for these reasons!
119+
</button>
120+
`
121+
})
122+
export class AppComponent {
123+
constructor(private afMessaging: AngularFireMessaging) { }
124+
requestPermission() {
125+
this.afMessaging.requestToken
126+
.subscribe(
127+
(token) => { console.log('Permission granted! Save to the server!', token); },
128+
(error) => { console.error(error); },
129+
);
130+
}
131+
}
132+
```
133+
134+
The `requestToken` observable uses the `tokenChanges` observable to listen to refreshes.
135+
136+
### Deleting tokens
137+
138+
Need to delete a user's token? Not a problem.
139+
140+
```ts
141+
import { Component } from '@angular/core';
142+
import { AngularFireMessaging } from '@angular/fire/messaging';
143+
import { mergeMap } from 'rxjs/operators';
144+
145+
@Component({
146+
selector: 'app-root',
147+
template: `
148+
<button (click)="deleteMyToken()">
149+
Delete my token plz
150+
</button>
151+
`
152+
})
153+
export class AppComponent {
154+
constructor(private afMessaging: AngularFireMessaging) { }
155+
deleteToken() {
156+
this.afMessaging.getToken
157+
.pipe(mergeMap(token => this.afMessaging.deleteToken(token)))
158+
.subscribe(
159+
(token) => { console.log('Deleted!'); },
160+
);
161+
}
162+
}
163+
```
164+
165+
The code above requests the current user's token and passes it to the `deleteToken()` observable.
166+
167+
### Subscribing to foreground messages
168+
169+
Once you have a user's token and they are subscribed, you can listen to messages in the foreground. The Firebase Messaging Service Worker handles background push notifications.
170+
171+
```ts
172+
import { Component } from '@angular/core';
173+
import { AngularFireMessaging } from '@angular/fire/messaging';
174+
175+
@Component({
176+
selector: 'app-root',
177+
template: `
178+
<button (click)="listen()">
179+
Get notified!
180+
</button>
181+
`
182+
})
183+
export class AppComponent {
184+
constructor(private afMessaging: AngularFireMessaging) { }
185+
listen() {
186+
this.afMessaging.messages
187+
.subscribe((message) => { console.log(message); });
188+
}
189+
}
190+
```
191+
192+
### Sending notifications
193+
194+
[Sending a notification](https://firebase.google.com/docs/cloud-messaging/js/first-message) requires a call to a server. You can do this directly with an HTTP call or you can even build a Cloud Function to do this in response to an event. A Cloud Function trigger is ideal because you have trusted access to the database and can securely look up tokens to send to the right user. If you want to send push notifications via HTTP requests you'll need to secure the API call. This is usually done with a Firebase Auth UID. On the server you can verify the UID with the Firebase Admin SDK and allow access to get a user's push id.
195+
196+
The [Firebase Admin SDK has helper functions for sending notifications](https://firebase.google.com/docs/cloud-messaging/admin/send-messages) to the user and subscribing them to topics, which [simplifies sending grouped messages](https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions).

0 commit comments

Comments
 (0)