How To Add Push Notifications In Angular
Tags: javascript, angular, webdev
Published: 2021-05-04 21:18:04

---
title: How To Add Push Notifications In Angular
published: true
date: 2021-05-04 20:02:52 UTC
tags: javascript, angular, webdev
canonical_url: 
---

 ![Developer Guide: How To Integrate Push Notifications in Angular](https://onesignal.com/blog/content/images/2021/05/integrating-push-notifications-in-angular--3-.png)

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

- **[Part 1: Set Up Your OneSignal Account](#part-1-set-up-your-onesignal-account)**
- [Web Configuration](#web-configuration)
- **[Part 2: Quick Push Notification Setup In Angular](#part-2-quick-push-notification-setup-in-angular)**
- [Allow Web Push Notifications](#allow-web-push-notifications)
- [Send Web Push Notifications](#send-web-push-notifications)
- **[Part 3: Advanced Push Notification Setup In Angular](#part-3-advanced-push-notification-setup-in-angular)**

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:**

- [Quick Angular Setup](https://github.com/OneSignal/OneSignal-Angular-Sample)
- [Advanced Angular Setup](https://github.com/OneSignal/OneSignal-Angular-Sample/tree/FINAL-CODE)

## Part 1: Set Up Your OneSignal Account

To begin, [login](https://app.onesignal.com/login) to your OneSignal account or [create a free account](https://app.onesignal.com/signup). 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](https://onesignal.com/blog/content/images/2021/05/set-up-onesignal-account-1.png)

Insert the name of your app or website. Select **_Web Push_** as your platform.

![Developer Guide: How To Integrate Push Notifications in Angular](https://onesignal.com/blog/content/images/2021/05/set-up-onesignal-account-2.png)

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](https://onesignal.com/blog/content/images/2021/05/web-configuration.png)

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](https://onesignal.com/blog/content/images/2021/05/push-slide-prompt.png)

A window will open with the configuration of our [push notification Slide Prompt](https://documentation.onesignal.com/docs/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](https://onesignal.com/blog/content/images/2021/05/permission-prompt-editor.png)

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](https://lh4.googleusercontent.com/camBSeQ9tHXO4YNeskPnOwxqhOf4Al3R9ZeHqnR-ryefOMVtuHwBlpMD-YwW87HrUPqqQK1xOYcGra_DAIm_66LDwweVTzCLPPXKSzKTYbMjCWz2bo6Vo6jpIRXjlOvsQOPBYi59)

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](https://lh4.googleusercontent.com/wfoLe_2cwZy3VvZqDa-c6p4zodUslzT_wcqtLoopYLkEb2oX_EMMG7ryEmhFdPvogOcPE8iviYIAn8OZY7V_Q7cdYjQzl8hXki-jKzPc4LBlXIOdRQgw-s_WGanprjOr9Slngyq4)

## 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.

```javascript
<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.

![Developer Guide: How To Integrate Push Notifications in Angular](https://lh5.googleusercontent.com/EO6rXfmDwh5ijF5FF-MrOLF2Moz6Q7d7d1TyGvMyEavXrQ2cueDzxHhosN-XkVZo1DUYjc7Mz3AY8dtFhY7Qq6x0goNHOJKsnqGOTz2WBClktHYSuI2B05NORRvn3XsPL98JavFv)

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:

```javascript
"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:

![Developer Guide: How To Integrate Push Notifications in Angular](https://lh3.googleusercontent.com/TXNNxMqU5B8lYe9XA4cdyfBmcYrCCCXazha8u94T4acvHiWc_xL6TtCEEPxLuFHH2dBSKbcj2kSiAOugtp5hyzOHWSlB-vw8Ijp8zkiRnZSreBz6O2a9UcWL7AcsnxR6m9pVNfFw)

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](https://onesignal.com/blog/content/images/2021/05/global-outcomes.png)

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](https://onesignal.com/blog/content/images/2021/05/new-push.png)

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:

```javascript
<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:

```javascript
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.

```javascript
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.

```javascript
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](https://documentation.onesignal.com/docs/web-push-sdk#initialization).

```javascript
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 `gOnInit()`, call the `onInit()` method from your OneSignal service. Your file will look like this:

```javascript
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](https://documentation.onesignal.com/docs/web-push-sdk).