8

I'm trying to integrate OneSignal into my Angular 2 app to receive push notifications. First I did a HelloWorld app using plain old HTML and it works beautifully. So I tried to include it into my Angular app, but users are not getting created/registered, and hence are not subscribed to receive any notifications.

Code excerpts:

index.html

<html>

<head>
  <meta charset="utf-8">
  <title>My Angular App</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <head>
    <link rel="manifest" href="/manifest.json">
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
  <script>
    var OneSignal = window.OneSignal || [];
    console.log("Init OneSignal");
    OneSignal.push(["init", {
      appId: "xxx-xxx-xxx-xxx-xxx",
      autoRegister: false,
      allowLocalhostAsSecureOrigin: true,
      notifyButton: {
        enable: true
      }
    }]);
    console.log('OneSignal Initialized');
    OneSignal.push(function () {
      console.log('Registered For Push');
      OneSignal.getUserId().then(function (userId) {
      console.log("User ID is", userId);
      });
    });
  </script>
  </head>
</head>

<body>
  <app-root>
    <div class="wrap">
      <div class="loading outer">
        <div class="loading inner"></div>
      </div>
    </div>
  </app-root>
</body>

</html>

The userId is always null.

I've checked the following:

  • App ID is correct
  • Permission for Notification is set to allow in the browser

Questions:

  • Is there a way to do all the init stuffs inside any component, say in the ngOnInit() method?
  • I would like to register for push when user clicks on a button inside my component rather than using the bell icon? How does one achieve that? ( I know that setting notifyButton to false will not show the notify bell)

P.S: Testing on Chrome using Angular CLI (Didn't work with FF or Safari)

PsyGik
  • 3,535
  • 1
  • 27
  • 44

2 Answers2

19

I'm afraid I presented another case of skimming the docs instead of actually reading it.

So I moved the code around a bit and this is what ended up working for me.

index.html

<html>

<head>
  <meta charset="utf-8">
  <title>My Angular App</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <head>
    <link rel="manifest" href="/manifest.json">
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async='async'></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
  </head>
</head>

<body>
  <app-root>
    <div class="wrap">
      <div class="loading outer">
        <div class="loading inner"></div>
      </div>
    </div>
  </app-root>
</body>

</html>

app.component.ts

export class AppComponent implements OnInit {
    .
    .
    .
    .
    ngOnInit() {
    var OneSignal = window['OneSignal'] || [];
    console.log("Init OneSignal");
    OneSignal.push(["init", {
      appId: "xxx-xxx-xxx-xxx",
      autoRegister: false,
      allowLocalhostAsSecureOrigin: true,
      notifyButton: {
        enable: false
      }
    }]);
    console.log('OneSignal Initialized');
    OneSignal.push(function () {
      console.log('Register For Push');
      OneSignal.push(["registerForPushNotifications"])
    });
    OneSignal.push(function () {
      // Occurs when the user's subscription changes to a new value.
      OneSignal.on('subscriptionChange', function (isSubscribed) {
        console.log("The user's subscription state is now:", isSubscribed);
        OneSignal.getUserId().then(function (userId) {
          console.log("User ID is", userId);
        });
      });
    });
    }
    .
    .
    .
}

Couple of things to note:

  • Listen to the subscriptionChange and then get the userid
  • subscriptionChange is also fired when user disables the notification manually from the browser.
  • autoRegister: false, will not prompt the 'Allow'/'Deny' option. So we have to call registerForPushNotifications. One can use this to prompt for push notification on a button click or something.

EDIT 2018

I've made a util class which I use across all my angular projects to reduce boilerplate code for onesignal.

https://gist.github.com/PsyGik/54a5e6cf5e92ba535272c38c2be773f1

PsyGik
  • 3,535
  • 1
  • 27
  • 44
  • 1
    Works also for Angular 5 with `angular-cli`. Thank you so much, you saved my day! :) – Maxime Lafarie Nov 14 '17 at 17:32
  • 2
    Where do you place the SDK? Only /assets/ is public! How do you solve this problem? GET http://localhost:4200/OneSignalSDKWorker.js?appId=xxxx 404 (Not Found) – Suisse Nov 23 '18 at 13:37
  • @Suisse, For my projects I have kept the files in the src folder. Then in .angular-cli.json just mention the location for the files. Only /assets/ is public is not true. You can add any file/folder path into the assets section in your cli.json file – PsyGik Nov 24 '18 at 06:39
  • In my case, OneSignal service Worker not working with Angular Service Worker. Onesignal team saying, that I have to place Angular serviceworker in a different folder and then need to import it. How is it possible? – Deepak swain Nov 26 '18 at 08:59
  • @Deepakswain, If you can share relevant code I might be able to help you out. Better yet, create another question with all details. – PsyGik Nov 26 '18 at 10:10
  • @PsyGik Thanks for that hint. Why I couldn't that info nowhere? thx. – Suisse Nov 26 '18 at 12:04
3

The simplest solution would be to just put the script provided by One Signal into your index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <meta
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
      name="viewport"
    />

    ...
    ...

    <link rel="manifest" href="/manifest.json" />
    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
    <script>
      var OneSignal = window.OneSignal || [];
      OneSignal.push(function() {
        OneSignal.init({
          appId: 'xxx-xxxx-xxxxx',
        });
      });
    </script>

    ...

Add the following into angular.json


    ...
    "architect": {
        "build": {
          "builder": "ngx-build-plus:build",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/favicon.png",
              "src/manifest.json", <-- this 
              "src/OneSignalSDKUpdaterWorker.js", <-- this 
              "src/OneSignalSDKWorker.js", <-- and finally this one
              "src/assets"
            ],
            "styles": [ 
              "src/styles.scss"
            ],
            "stylePreprocessorOptions": {
              "includePaths": ["src/assets/sass"]
            },
            "scripts": []
          },
          ...

And place the manifest and the 2 *.js file into /src/*

That's it. You will need to publish it to your server and not your localhost:4200. I got it to work on mine using this method. Hope that helps