メインコンテンツへスキップ

概要

このガイドでは、onesignal-ngxパッケージを使用してAngularアプリケーションでプッシュ通知を設定する方法を説明します。インストールから設定、サービスワーカーの管理まで、すべてをカバーしています。

要件

  • 設定済みのOneSignalアプリとプラットフォーム。開始するには、Web Push Setupを参照してください。

インストール

お好みのパッケージマネージャーを使用してonesignal-ngxパッケージをインストールします:
npm install --save onesignal-ngx

初期化

OneSignalサービスをインポートし、ルートコンポーネントで初期化します:
ts
import { OneSignal } from 'onesignal-ngx';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private oneSignal: OneSignal) {
    this.oneSignal.init({
      appId: 'YOUR-ONESIGNAL-APP-ID',
    });
  }
}

初期化の待機

init()が返すPromiseは2つの方法で処理できます:
ts
// オプション1: async/await
await this.oneSignal.init({ appId: 'YOUR-APP-ID' });
// 他のロジックを続行

// オプション2: .then()
this.oneSignal.init({ appId: 'YOUR-APP-ID' }).then(() => {
  // OneSignal APIと安全にやり取りできます
});

初期化オプションのカスタマイズ

追加のinitパラメータを使用して初期化をカスタマイズできます。

サービスワーカーの設定

Angularの独自のサービスワーカー(PWAセットアップで使用)との競合を避けるため、OneSignalサービスワーカーに固有のスコープとパスを指定します。 まだ行っていない場合は、OneSignalサービスワーカーファイルをダウンロードしてサイトに追加する必要があります。 OneSignalSDKWorker.jsファイルは公開アクセス可能である必要があります。publicディレクトリ、トップレベルのルート、またはサブディレクトリに配置できます。ただし、サブディレクトリに配置する場合や、サイトに別のサービスワーカーがある場合は、必ずパスを指定してください。詳細については、OneSignal Service Workerを参照してください。
オプション説明
serviceWorkerParamOneSignalワーカーによって制御されるスコープ。推奨: カスタムサブパスを使用します(例:"/onesignal/")。
serviceWorkerPathホストされているOneSignalサービスワーカーファイルへのパス(例:"onesignal/OneSignalSDKWorker.js")。公開アクセス可能である必要があります。
例:
this.oneSignal.init({
  appId: 'YOUR-APP-ID',
  serviceWorkerParam: {
    scope: '/onesignal/'
  },
  serviceWorkerPath: 'onesignal/OneSignalSDKWorker.js'
});

ワーカーのホスティング

  • パブリックルート(デフォルト):/OneSignalSDKWorker.js
  • カスタムフォルダ(推奨):例:前のステップで設定した/onesignal/OneSignalSDKWorker.js

サービスワーカーのホスティングを確認する

ブラウザでパスにアクセスして、アクセス可能であることを確認します。 ルートを使用した場合:
https://your-site.com/OneSignalSDKWorker.js
例のパスを使用した場合:
https://your-site.com/onesignal/OneSignalSDKWorker.js
有効なJavaScriptが返されるはずです。

Angular CLIユーザーにとって重要

ファイルが提供されていない場合は、angular.jsonassets配列にリストされていることを確認してください:
json
"assets": [
  "src/assets",
  "onesignal/OneSignalSDKWorker.js"
]

重要な注意事項

  • 開発環境での重複初期化を避ける
    • 開発環境でテストする際、OneSignal SDKが2回初期化され、コンソールエラーが発生することがあります。
    • これは、<React.StrictMode>により、開発環境でエフェクトが2回実行されるために発生します。解決するには、開発中にルートコンポーネントから<React.StrictMode>を削除してください。
Strictモードは開発にのみ影響し、本番ビルドには影響しません。

Testing the OneSignal SDK integration

This guide helps you verify that your OneSignal SDK integration is working correctly by testing push notifications and subscription registration.

Check web push subscriptions

1

Launch your site on a test device.

  • Use Chrome, Firefox, Edge, or Safari while testing.
  • Do not use Incognito or private browsing mode. Users cannot subscribe to push notifications in these modes.
  • The prompts should appear based on your permission prompts configuration.
  • Click Allow on the native prompt to subscribe to push notifications.
Browser native permission prompt asking the user to allow or block notifications
2

Check your OneSignal dashboard

  • Go to Audience > Subscriptions.
  • You should see a new entry with the status Subscribed.
OneSignal dashboard Subscriptions page showing a web push subscription with Subscribed status
You have successfully created a web push subscription. Web push subscriptions are created when users first subscribe to push notifications on your site.

Set up test subscriptions

Test subscriptions are helpful for testing a push notification before sending a message.
1

Add to Test Subscriptions.

In the dashboard, next to the subscription, click the Options (three dots) button and select Add to Test Subscriptions.
Options menu on a subscription showing the Add to Test Subscriptions option
2

Name your subscription.

Name the subscription so you can easily identify your device later in the Test Subscriptions tab.
3

Create a test users segment.

Go to Audience > Segments > New Segment.
4

Name the segment.

Name the segment Test Users (the name is important because it will be used later).
5

Add the Test Users filter and click Create Segment.

Segment editor with Test Users filter selected and the segment named Test Users
You have successfully created a segment of test users. You can now test sending messages to this individual device and groups of test users.

Send test push via API

1

Get your App API Key and App ID.

In your OneSignal dashboard, go to Settings > Keys & IDs.
2

Update the provided code.

Replace YOUR_APP_API_KEY and YOUR_APP_ID in the code below with your actual keys. This code uses the Test Users segment created earlier.
curl -X POST --url 'https://api.onesignal.com/notifications' \
  --header 'content-type: application/json; charset=utf-8' \
  --header 'authorization: Key YOUR_APP_API_KEY' \
  --data '{
    "app_id": "YOUR_APP_ID",
    "target_channel": "push",
    "name": "Testing basic setup",
    "headings": {
      "en": "👋"
    },
    "contents": {
      "en": "Hello world!"
    },
    "included_segments": [
      "Test Users"
    ],
    "chrome_web_image": "https://avatars.githubusercontent.com/u/11823027?s=200&v=4"
  }'
3

Run the code.

Run the code in your terminal.
4

Check images and confirmed delivery.

If all setup steps were completed successfully, the test subscriptions should receive a notification.
Only Chrome supports images. Images will appear small in the collapsed notification view. Expand the notification to see the full image.
Expanded Chrome push notification on macOS displaying a custom image
5

Check for confirmed delivery.

In your dashboard, go to Delivery > Sent Messages, then click the message to view stats. You should see the confirmed stat, meaning the device received the push.
Safari does not support Confirmed Delivery.

Push notification message reports

View delivery, click, and conversion stats for your push notifications.
You have successfully sent a notification via the API to a segment.
If notifications are not arriving, contact support@onesignal.com with the following:
  • The API request and response (copy-paste into a .txt file)
  • Your Subscription ID
  • Your website URL with the OneSignal code

User identification

The previous section covered creating web push Subscriptions. This section expands to identifying Users across all their subscriptions (including push, email, and SMS) using the OneSignal SDK. It covers External IDs, tags, multi-channel subscriptions, privacy, and event tracking to help you unify and engage users across platforms.

Assign External ID

Use an External ID to identify users consistently across devices, email addresses, and phone numbers using your backend’s user identifier. This ensures your messaging stays unified across channels and 3rd party systems (especially important for Integrations). Set the External ID with the SDK’s login method each time a user is identified by your app.
OneSignal generates unique read-only IDs for subscriptions (Subscription ID) and users (OneSignal ID).As users download your app on different devices, subscribe to your website, and/or provide you email addresses and phone numbers outside of your app, new subscriptions will be created.Setting the External ID via the SDK is highly recommended to identify users across all their subscriptions, regardless of how they are created.

Add data tags

Tags are key-value pairs of string data you can use to store user properties (like username, role, or preferences) and events (like purchase_date, game_level, or user interactions). Tags power advanced Message Personalization and Segmentation allowing for more advanced use cases. Set tags with the SDK’s addTag and addTags methods as events occur in your app. In this example, the user reached level 6 identifiable by the tag called current_level set to a value of 6.
OneSignal user profile showing a data tag named current_level with value 6
You can create a segment of users with a level between 5 and 10, then use that segment to send targeted and personalized messages:
Segment editor filtering users where current_level is greater than 4 and less than 10
Push notification composer targeting the Level 5-10 segment with a personalized message

Add email and/or SMS subscriptions

The OneSignal SDK creates web push subscriptions automatically when users opt in. You can also reach users through email and SMS channels by creating the corresponding subscriptions. If the email address or phone number already exists in the OneSignal app, the SDK adds it to the existing user. It does not create duplicates. You can view unified users via Audience > Users in the dashboard or with the View user API.
OneSignal user profile showing push, email, and SMS subscriptions linked by External ID
Best practices for multi-channel communication
  • Obtain explicit consent before adding email or SMS subscriptions.
  • Explain the benefits of each communication channel to users.
  • Provide channel preferences so users can select which channels they prefer.

To control when OneSignal collects user data, use the SDK’s consent gating methods: For more on privacy and security:

Listen to push, user, and in-app events

Use SDK listeners to react to user actions and state changes. The SDK provides several event listeners you can hook into. See the SDK reference guide for more details.

Push notification events

User state changes


Advanced setup & capabilities

Explore more capabilities to enhance your integration:

Web SDK setup & reference

Congratulations! You’ve successfully completed the Web SDK setup guide.

Need help?Chat with our Support team or email support@onesignal.comPlease include:
  • Details of the issue you’re experiencing and steps to reproduce if available
  • Your OneSignal App ID
  • The External ID or Subscription ID if applicable
  • The URL to the message you tested in the OneSignal Dashboard if applicable
  • Any relevant logs or error messages
We’re happy to help!