OneSignal Integration with Angular

I am trying to integrate OneSignal into my Angular 2 app to receive push notifications. I first made a HelloWorld app using plain old HTML and it works great. So I tried to include it in my Angular app, but the users are not created / registered and therefore do not subscribe 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>

      

UserId is always null.

I checked the following:

  • App id is correct
  • Permission for notification is set to permission in browser

Questions:

  • Is there a way to make all init elements inside any component, for example in the ngOnInit () method?
  • I would like to register for a click when the user clicks on a button inside my component rather than using the bell icon? How can this be achieved? (I know that setting notifyButton to false will not show the notification ringtone)

PS: Testing in Chrome with Angular CLI (doesn't work with FF or Safari)

+6


source to share


2 answers


I'm afraid I presented another case where I was looking through documents rather than reading them.

So I moved the code around a bit and this is what ultimately worked 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 subscription changes to a new value.
      OneSignal.on('subscriptionChange', function (isSubscribed) {
        console.log("The user subscription state is now:", isSubscribed);
        OneSignal.getUserId().then(function (userId) {
          console.log("User ID is", userId);
        });
      });
    });
    }
    .
    .
    .
}

      



A few things to note:

  • Listen for the change subscriptionChange

    and then get the user id
  • subscriptionChange

    also fired when the user manually disables the notification from the browser.
  • autoRegister: false,

    does not prompt for the Allow / Deny option. Therefore we have to call registerForPushNotifications

    . You can use this to request a push notification for a button click or something.

EDIT 2018

I created a utility class that I use in all of my angular projects to reduce the boilerplate for signal code.

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

+14


source


The simplest solution would be to just put the script provided by One Signal in 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 to 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 put your manifest and 2 * .js file in /src/*

It. You will need to publish it to your server, not localhost: 4200. I made it work on mine using this method. hope this helps

+1


source







All Articles