DEV Community

loading...
OneSignal

How To Integrate Push Notifications in Angular

Pato
Google Developer Expert on Angular and Web Technologies | Auth0 Ambassador | Media Developer Expert for Cloudinary | Twilio Champ | Technical Coach at SpringBoard | Google Women Techmaker
Originally published at onesignal.com on ・7 min read

Developer Guide: How To Integrate Push Notifications in Angular

It’s no secret that push notifications can help you engage and retain app users. In this tutorial, we'll show you how to integrate with OneSignal in order to leverage push notifications in your Angular app.

OneSignal & Your Browser's Push API

The browser's push API gives web applications the ability to receive messages from a server whether or not the web app is in the foreground or currently loaded on a user agent. This lets you deliver asynchronous notifications and updates to users who opt-in, resulting in better engagement with timely new content.

This tutorial will cover how to integrate OneSignal Push Notifications into your app using our typical setup process. Part one of this guide covers the OneSignal setup process. Part two of this guide covers how to integrate with Angular using a basic setup method. Part three covers an advanced setup method you can implement after completing the basic setup. The advanced setup will unlock even more message customization and automation opportunities for your website or app.

Guide Overview

This tutorial requires some basic knowledge of Angular. I'm using Angular 11.2 and NodeJS version 14.0. If you don't have Angular, create a new Angular project using the Angular CLI.

Additional Angular Setup Resources:

Part 1: Set Up Your OneSignal Account

To begin, login to your OneSignal account or create a free account. Then, click on the blue button entitled New App/Website to configure your OneSignal account to fit your app or website.

Developer Guide: How To Integrate Push Notifications in Angular

Insert the name of your app or website. Select Web Push as your platform.

Developer Guide: How To Integrate Push Notifications in Angular

Click on the blue button entitled, Next: Configure Your Platform.

Web Configuration

Under Choose Integration , select the Typical Site option.

In the _ Site Setup _ section, enter your chosen web configuration. In my case, the configuration looks like this:

Developer Guide: How To Integrate Push Notifications in Angular

Notice for testing purposes I’m entering my localhost URL (http://localhost:4401). If you are doing the same, make sure you click on the LOCAL TESTING option. This will ensure to treat HTTP localhost as HTTPS for testing.

Under _ Permission Prompt Setup , you will see three vertical blue dots under the _ Actions _ header on the far right side of the screen. Click on the blue dots and select **_Edit** from the drop-down menu.

Developer Guide: How To Integrate Push Notifications in Angular

A window will open with the configuration of our push notification Slide Prompt. Confirm that Auto-prompt is enabled (toggled to the right).

Under _ Show When , you can change the second increment to alter how long your slide prompt will delay after a user visits your page. You can leave it as it is, or you can reduce the seconds so that your prompt appears sooner. Once you've input your chosen delay increment, click the grey **_Done** button located at the bottom right corner of the window.

Developer Guide: How To Integrate Push Notifications in Angular

After clicking _ Done _, scroll down to the bottom of the page and click _ Save _ to save your auto-prompt selections.

You will be redirected to a different page with an important step: Downloading the SDK files. Click DOWNLOAD ONESIGNAL SDK FILES and save them on your computer to retrieve later.

Developer Guide: How To Integrate Push Notifications in Angular

Under the section entitled Add Code to Site , you will see a grey button that allows you to copy the code snippet. Click the grey _ COPY CODE _ button.

Developer Guide: How To Integrate Push Notifications in Angular

Part 2: Quick Push Notification Setup In Angular

In your Angular project folder, navigate to the index.html file. Inside of the head HTML tag, paste the code you previously copied from the OneSignal page.

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
window.OneSignal = window.OneSignal || [];
    OneSignal.push(function() {
        OneSignal.init({
            appId: "YOUR-APP-ID",
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Now, locate the SDK files you downloaded on your computer and insert them inside of the src folder of your Angular app.

Developer Guide: How To Integrate Push Notifications in Angular

After you have inserted the SDK files into your Angular project, you'll need to make Angular aware of those SDK files. To do so, open the angular.json file and locate the architecture property. Inside of that property, you will see another property called assets, at the bottom of this property, add the location of the OneSignal SDKs.

Your angular.json should look like this:

"assets": [
              "src/favicon.ico",
              "src/assets",
              "src/OneSignalSDKUpdaterWorker.js",
              "src/OneSignalSDKWorker.js",
            ],
Enter fullscreen mode Exit fullscreen mode

Allow Web Push Notifications

Run the Angular app and visit your website. You should see the following prompt appear after your chosen time delay interval:

Developer Guide: How To Integrate Push Notifications in Angular

Click on the blue Allow button to enable push notifications on your browser.

Send Web Push Notifications

It’s time to send your first web push notification! To do so, login to your OneSignal account and navigate to the Dashboard tab. On the dashboard page, click on the blue button that says New Push.

Developer Guide: How To Integrate Push Notifications in Angular

You will be redirected to a new window that will allow you to customize your push notification. Under Audience , make sure that _ Send to Subscribed Users _ is selected. Then, create your message by adding your message title, content, and an image. Because this is the first notification your subscribers will receive, you may choose to craft a simple welcome message to confirm that they've been subscribed and reinforce the value that notifications will provide.

Under the Delivery Schedule section, select _ Immediately _ and Send to everyone at the same time to send to all your current web push subscribers. If you have just finished setting up your OneSignal account, chances are you're the first and only subscriber. If your app or website is heavily trafficked and other users have already opted in to receive push notifications, you may want to select Send to particular segment(s) to test your message out on a specific audience. When you're ready to send your message, click on the blue _ Review and Send _ button at the bottom of the screen.

Developer Guide: How To Integrate Push Notifications in Angular

A small popup will appear for you to review your message. Once you are satisfied, click on the blue _ Send Message _ button. You should receive a web push notification on your device! 🚀

Part 3: Advanced Push Notification Setup In Angular

If you want the ability to use OneSignal across your entire Angular app, complete these advanced push notification setup steps after completing the quick push notification setup.

Inside of your index.html file, remove the following code:

<script>
window.OneSignal = window.OneSignal || [];
    OneSignal.push(function() {
        OneSignal.init({
            appId: "YOUR-APP-ID",
        });
});
</script>
Enter fullscreen mode Exit fullscreen mode

In your root folder, create a new file called globals.ts. In this file, you will insert the following code:

export{}
declare global {
    interface Window {
        OneSignal: any;
    }
}
Enter fullscreen mode Exit fullscreen mode

The code above will allow you to make use of the window.OneSignal object without triggering any TS and compiler errors. Now that you have the globals.ts file created, import it into your polyfills.ts file.

import 'globals';
Enter fullscreen mode Exit fullscreen mode

Now it's time to create your OneSignal service inside of your Angular app. I have created one using the Angular CLI. The name of my service file is one-signal.service.ts. After creating the service, you will create an onLoad() method that will ensure that the SDK script we added inside of the index.html has been loaded since it's an async operation.

async onLoad(): Promise<any> {
    window.OneSignal = window.OneSignal || [];
    return new Promise((resolve) => {
        window.OneSignal.push(function() {
            resolve(window.OneSignal);
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

In the OneSignal service, create a new method called onInit(). Inside of the method you will call the onLoad() and you will initialize OneSignal.

onInit():void {
    this.onLoad().then((OneSignal)=>{
        OneSignal.init({
            appId: "YOUR-APP-ID",
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

Next, open your app.component.ts file and inject the OneSignal services you just created. Inside of the gOnInit(), call the onInit() method from your OneSignal service. Your file will look like this:

import { Component, OnInit } from '@angular/core';
import { OneSignalService } from './one-signal.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
    title = 'OneSignal-Angular';

    constructor(private os: OneSignalService){}

    ngOnInit() {
        this.os.onInit();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, you can keep expanding your code to make use of different features of the OneSignal SDK across your Angular app. To learn more about the Web Push SDK visit our web push SDK documentation.

Discussion (0)

Forem Open with the Forem app