填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

SwPush

Subscribe and listen to Web Push Notifications through Angular Service Worker.

      
      class SwPush {
  messages: Observable<object>
  notificationClicks: Observable<{...}
  subscription: Observable<PushSubscription | null>
  isEnabled: boolean
  requestSubscription(options: { serverPublicKey: string; }): Promise<PushSubscription>
  unsubscribe(): Promise<void>
}
    

参见

属性

属性说明
messages: Observable<object>只读

Emits the payloads of the received push notification messages.

notificationClicks: Observable<{ action: string; notification: NotificationOptions & { title: string; }; }>只读

Emits the payloads of the received push notification messages as well as the action the user interacted with. If no action was used the action property contains an empty string ''.

Note that the notification property does not contain a Notification object but rather a NotificationOptions object that also includes the title of the Notification object.

subscription: Observable<PushSubscription | null>只读

Emits the currently active PushSubscription associated to the Service Worker registration or null if there is no subscription.

isEnabled: boolean只读

True if the Service Worker is enabled (supported by the browser and enabled via ServiceWorkerModule).

方法

Subscribes to Web Push Notifications, after requesting and receiving user permission.

requestSubscription(options: { serverPublicKey: string; }): Promise<PushSubscription>
      
      requestSubscription(options: { serverPublicKey: string; }): Promise<PushSubscription>
    
参数
options object

An object containing the serverPublicKey string.

返回值

Promise<PushSubscription>: A Promise that resolves to the new subscription object.

Unsubscribes from Service Worker push notifications.

unsubscribe(): Promise<void>
      
      unsubscribe(): Promise<void>
    
参数

没有参数。

返回值

Promise<void>: A Promise that is resolved when the operation succeeds, or is rejected if there is no active subscription or the unsubscribe operation fails.

使用说明

You can inject a SwPush instance into any component or service as a dependency.

import {SwPush} from '@angular/service-worker'; /* . . . */ export class AppComponent { constructor(readonly swPush: SwPush) {} /* . . . */ }
app.component.ts
      
      import {SwPush} from '@angular/service-worker';
/* . . . */
export class AppComponent {
  constructor(readonly swPush: SwPush) {}
/* . . . */
}
    

To subscribe, call SwPush.requestSubscription(), which asks the user for permission. The call returns a Promise with a new PushSubscriptioninstance.

private async subscribeToPush() { try { const sub = await this.swPush.requestSubscription({ serverPublicKey: PUBLIC_VAPID_KEY_OF_SERVER, }); // TODO: Send to server. } catch (err) { console.error('Could not subscribe due to:', err); } }
app.component.ts
      
      private async subscribeToPush() {
  try {
    const sub = await this.swPush.requestSubscription({
      serverPublicKey: PUBLIC_VAPID_KEY_OF_SERVER,
    });
    // TODO: Send to server.
  } catch (err) {
    console.error('Could not subscribe due to:', err);
  }
}
    

A request is rejected if the user denies permission, or if the browser blocks or does not support the Push API or ServiceWorkers. Check SwPush.isEnabled to confirm status.

Invoke Push Notifications by pushing a message with the following payload.

{ "notification": { "actions": NotificationAction[], "badge": USVString "body": DOMString, "data": any, "dir": "auto"|"ltr"|"rtl", "icon": USVString, "image": USVString, "lang": DOMString, "renotify": boolean, "requireInteraction": boolean, "silent": boolean, "tag": DOMString, "timestamp": DOMTimeStamp, "title": DOMString, "vibrate": number[] } }
      
      {
  "notification": {
    "actions": NotificationAction[],
    "badge": USVString
    "body": DOMString,
    "data": any,
    "dir": "auto"|"ltr"|"rtl",
    "icon": USVString,
    "image": USVString,
    "lang": DOMString,
    "renotify": boolean,
    "requireInteraction": boolean,
    "silent": boolean,
    "tag": DOMString,
    "timestamp": DOMTimeStamp,
    "title": DOMString,
    "vibrate": number[]
  }
}
    

Only title is required. See Notification instance properties.

While the subscription is active, Service Worker listens for PushEvent occurrences and creates Notification instances in response.

Unsubscribe using SwPush.unsubscribe().

An application can subscribe to SwPush.notificationClicks observable to be notified when a user clicks on a notification. For example:

this.swPush.notificationClicks.subscribe( ({action, notification}) => { // TODO: Do something in response to notification click. });
app.component.ts
      
      this.swPush.notificationClicks.subscribe(
    ({action, notification}) => {
        // TODO: Do something in response to notification click.
    });