Skip to content

docs(*): Document AngularFireFunctions and AngularFireMessaging #1856

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

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

### Deploy to Firebase Hosting
### Send push notifications
- [Getting started with Firebase Messaging](docs/messaging/messaging.md)

### Directly call Cloud Functions
- [Getting started with Callable Functions](docs/functions/functions.md)

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

### Ionic
Expand Down
70 changes: 70 additions & 0 deletions docs/functions/functions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# AngularFireFunctions

> 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.

### Import the `NgModule`

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.

```ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from '@angular/fire';
import { AngularFireFunctionsModule } from '@angular/fire/functions';
import { environment } from '../environments/environment';

@NgModule({
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireFunctionsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```

### Injecting the AngularFireFunctions service

Once the `AngularFireFunctionsModule` is registered you can inject the `AngularFireFunctions` service.

```ts
import { Component } from '@angular/core';
import { AngularFireFunctions } from '@angular/fire/functions';

@Component({
selector: 'app-component',
template: ``
})
export class AppComponent {
constructor(private fns: AngularFireFunctions) { }
}
```

### Creating a callable function

AngularFireFunctions is super easy. You create a function on the server side and then "call" it by its name with the client library.

| method | |
| ---------|--------------------|
| `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. |
```ts

import { Component } from '@angular/core';
import { AngularFireStorage } from '@angular/fire/functions';

@Component({
selector: 'app-root',
template: `{ data$ | async }`
})
export class AppComponent {
constructor(private fns: AngularFireFunctions) {
const callable = fns.httpsCallable('my-fn-name');
this.data$ = callable({ name: 'some-data' });
}
}
```

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.
196 changes: 196 additions & 0 deletions docs/messaging/messaging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# AngularFireMessaging

> The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API.

### AngularFireMessaging is not compatible with the Angular Service Worker

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.

### Import the `NgModule`

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.

```ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from '@angular/fire';
import { AngularFireStorageModule } from '@angular/fire/messaging';
import { environment } from '../environments/environment';

@NgModule({
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireMessagingModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```

### Setting up the Firebase Messaging Service Worker

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).

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:

```json
"assets": [
"assets",
"favicon.ico",
"firebase-messaging-sw.js",
"manifest.json"
],
```

### Requesting permission

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.

```ts
import { Component } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';

@Component({
selector: 'app-root',
template: `
<button (click)="requestPermission()">
Hey this is a chat app, you should let us send you notifications for these reasons!
</button>
`
})
export class AppComponent {
constructor(private afMessaging: AngularFireMessaging) { }
requestPermission() {
this.afMessaging.requestPermission
.subscribe(
() => { console.log('Permission granted!'); },
(error) => { console.error(error); },
);
}
}
```

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.

```ts
import { Component } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { mergeMapTo } from 'rxjs/operators';

@Component({
selector: 'app-root',
template: `
<button (click)="requestPermission()">
Hey this is a chat app, you should let us send you notifications for these reasons!
</button>
`
})
export class AppComponent {
constructor(private afMessaging: AngularFireMessaging) { }
requestPermission() {
this.afMessaging.requestPermission
.pipe(mergeMapTo(this.afMessaging.tokenChanges))
.subscribe(
(token) => { console.log('Permission granted! Save to the server!', token); },
(error) => { console.error(error); },
);
}
}
```

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.

### Shortcutting token requests

An easier way of requesting permission and getting tokens is with the `requestToken` observable. It combines the two steps above into one observable.

```ts
import { Component } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';

@Component({
selector: 'app-root',
template: `
<button (click)="requestPermission()">
Hey this is a chat app, you should let us send you notifications for these reasons!
</button>
`
})
export class AppComponent {
constructor(private afMessaging: AngularFireMessaging) { }
requestPermission() {
this.afMessaging.requestToken
.subscribe(
(token) => { console.log('Permission granted! Save to the server!', token); },
(error) => { console.error(error); },
);
}
}
```

The `requestToken` observable uses the `tokenChanges` observable to listen to refreshes.

### Deleting tokens

Need to delete a user's token? Not a problem.

```ts
import { Component } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { mergeMap } from 'rxjs/operators';

@Component({
selector: 'app-root',
template: `
<button (click)="deleteMyToken()">
Delete my token plz
</button>
`
})
export class AppComponent {
constructor(private afMessaging: AngularFireMessaging) { }
deleteToken() {
this.afMessaging.getToken
.pipe(mergeMap(token => this.afMessaging.deleteToken(token)))
.subscribe(
(token) => { console.log('Deleted!'); },
);
}
}
```

The code above requests the current user's token and passes it to the `deleteToken()` observable.

### Subscribing to foreground messages

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.

```ts
import { Component } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';

@Component({
selector: 'app-root',
template: `
<button (click)="listen()">
Get notified!
</button>
`
})
export class AppComponent {
constructor(private afMessaging: AngularFireMessaging) { }
listen() {
this.afMessaging.messages
.subscribe((message) => { console.log(message); });
}
}
```

### Sending notifications

[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.

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).