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.

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

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:

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.

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.


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.

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.

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>

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

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",
            ],

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:


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.

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.

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>

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;
	}
}

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';

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);
		});
	});
}

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",
		});
	});
}

Next, open your app.component.ts file and inject the OneSignal services you just created. Inside of the ngOnInit(), 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();
    }
}

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.