Visão geral
Este guia explica como configurar notificações push em seu aplicativo Angular usando o pacoteonesignal-ngx, cobrindo tudo, desde a instalação até a configuração e gerenciamento do service worker.
Requisitos
- Aplicativo e plataforma OneSignal configurados. Consulte Configuração de Web Push para começar.
Instalação
Instale o pacoteonesignal-ngx usando seu gerenciador de pacotes preferido:
Inicialização
Importe o serviço OneSignal e inicialize-o em seu componente raiz:Aguardando a inicialização
Você pode lidar com a promessa retornada porinit() de duas maneiras:
Personalizando opções de inicialização
Você pode personalizar sua inicialização com parâmetrosinit adicionais.
Configurações do Service Worker
Para evitar conflitos com o próprio service worker do Angular (usado em configurações PWA), especifique um escopo e caminho exclusivos para o service worker do OneSignal. Se você ainda não o fez, precisará baixar o arquivo Service Worker do OneSignal para adicionar ao seu site. O arquivoOneSignalSDKWorker.js deve ser publicamente acessível. Você pode colocá-lo no seu diretório public, raiz de nível superior ou um subdiretório. No entanto, se você estiver colocando o arquivo em um subdiretório e/ou tiver outro service worker para seu site, certifique-se de especificar o caminho. Consulte Service Worker do OneSignal para detalhes.
| Opção | Descrição |
|---|---|
serviceWorkerParam | Escopo controlado pelo worker do OneSignal. Recomendação: Use um subcaminho personalizado (ex: "/onesignal/"). |
serviceWorkerPath | Caminho para seu arquivo de service worker do OneSignal hospedado (ex: "onesignal/OneSignalSDKWorker.js"). Deve ser publicamente acessível. |
Hospedando o worker
- Raiz pública (padrão):
/OneSignalSDKWorker.js - Pasta personalizada (recomendado): ex:
/onesignal/OneSignalSDKWorker.jsconforme definido na etapa anterior.
Verificar hospedagem do service worker
Visite o caminho no seu navegador para confirmar se está acessível. Se você usou a raiz:Importante para usuários do Angular CLI
Se o arquivo não estiver sendo servido, certifique-se de que está listado no seuangular.json no array assets:
Notas importantes
- Evite inicialização duplicada em desenvolvimento
- Ao testar em um ambiente de desenvolvimento, você pode ver o SDK do OneSignal inicializar duas vezes, o que pode causar erros no console.
- Isso acontece devido ao
<React.StrictMode>fazer com que os efeitos sejam executados duas vezes no desenvolvimento. Para resolver isso, remova<React.StrictMode>do seu componente raiz durante o desenvolvimento.
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
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.

Web push native permission prompt
Check your OneSignal dashboard
- Go to Audience > Subscriptions.
- You should see a new entry with the status Subscribed.

Dashboard showing subscription with 'Subscribed' status
Set up test subscriptions
Test subscriptions are helpful for testing a push notification before sending a message.Add to Test Subscriptions.

Adding a device to Test Subscriptions
Name your subscription.

Dashboard showing the 'Name your subscription' field
Create a test users segment.
Name the segment.
Test Users (the name is important because it will be used later).Add the Test Users filter and click Create Segment.

Creating a 'Test Users' segment with the Test Users filter
Send test push via API
Get your App API Key and App ID.
Update the provided code.
YOUR_APP_API_KEY and YOUR_APP_ID in the code below with your actual keys. This code uses the Test Users segment we created earlier.Run the code.
Check images and confirmed delivery.

Expanded push notification with image on Chrome macOS
Check for confirmed delivery.

Delivery stats showing confirmed delivery

Confirmed delivery at the device level in Audience Activity
support@onesignal.com with the following information:- Copy-paste the API request and response into a
.txtfile - Your Subscription ID
- Your website URL with the OneSignal code
User identification
Previously, we demonstrated how to create web push Subscriptions. Now we’ll expand to identifying Users across all their subscriptions (including push, email, and SMS) using the OneSignal SDK. We’ll cover 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 our SDK’slogin method each time they are identified by your app.
Add data tags
Tags are key-value pairs of string data you can use to store user properties (likeusername, 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 our SDK 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.

A user profile in OneSignal with a tag called "current_level" set to "6"

Segment editor showing a segment targeting users with a current_level value of greater than 4 and less than 10

Screenshot showing a push notification targeting the Level 5-10 segment with a personalized message
Add email and/or SMS subscriptions
Earlier we saw how our SDK creates web push subscriptions to send push. You can also reach users through emails and SMS channels by creating the corresponding subscriptions.- Use the
addEmailmethod to create email subscriptions. - Use the
addSmsmethod to create SMS subscriptions.

A user profile with push, email, and SMS subscriptions unified by External ID
- 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.
Privacy & user consent
To control when OneSignal collects user data, use the SDK’s consent gating methods:setConsentRequired(true): Prevents data collection until consent is given.setConsentGiven(true): Enables data collection once consent is granted.
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 for you to hook into. See our SDK reference guide for more details.Push notification events
- Click event listener: Detect when a notification is tapped.
- Foreground lifecycle listener: Control how notifications behave in foreground.
User state changes
- User state change event listener: Detect when the External ID is set.
- Permission observer: Track the user’s specific interaction with the native push permission prompt.
- Push subscription change observer: Track when the push subscription status changes.
Advanced setup & capabilities
Explore more capabilities to enhance your integration:- 🔁 Migrating to OneSignal from another service
- 🔌 Integrations
- 🛎️ Action buttons
- 🌐 Multi-language messaging
- 🛡️ Identity Verification
- 📊 Custom Outcomes
Web SDK setup & reference
Make sure you’ve enabled all key features by reviewing the Web push setup guide. For full details on available methods and configuration options, visit the Web SDK reference.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