Skip to content

Instantly share code, notes, and snippets.

@PsyGik
Created November 24, 2018 06:49
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save PsyGik/54a5e6cf5e92ba535272c38c2be773f1 to your computer and use it in GitHub Desktop.
Save PsyGik/54a5e6cf5e92ba535272c38c2be773f1 to your computer and use it in GitHub Desktop.
OneSignal Angular TypeScript
import {Injectable} from '@angular/core';
import {Cache} from '../utils/storage.provider'; // Decorator to access local storage
let OneSignal;
const url = '';
@Injectable()
export class OneSignalService {
@Cache({pool: 'OneSignal'}) oneSignalInit; // to check if OneSignal is already initialized.
@Cache({pool: 'OneSignal'}) oneSignalId: any; // store OneSignalId in localStorage
@Cache({pool: 'Token'}) userSession: any; // User Session management token
constructor() {
console.log('OneSignal Service Init', this.oneSignalInit);
}
// Call this method to start the onesignal process.
public init() {
this.oneSignalInit ? console.log('Already Initialized') : this.addScript('https://cdn.onesignal.com/sdks/OneSignalSDK.js', (callback) => {
console.log('OneSignal Script Loaded');
this.initOneSignal();
})
}
addScript(fileSrc, callback) {
const head = document.getElementsByTagName('head')[0];
const script = document.createElement('script');
script.type = 'text/javascript';
script.onload = callback;
script.src = fileSrc;
head.appendChild(script);
}
initOneSignal() {
OneSignal = window['OneSignal'] || [];
OneSignal.sendTag('user_id', this.userSession.user, (tagsSent) => {
// Callback called when tags have finished sending
console.log('OneSignal Tag Sent', tagsSent);
});
console.log('Init OneSignal');
OneSignal.push(['init', {
appId: 'xxx-xxx-xxx-xxx',
autoRegister: true,
allowLocalhostAsSecureOrigin: true,
notifyButton: {
enable: false,
},
}]);
console.log('OneSignal Initialized');
this.checkIfSubscribed();
}
subscribe() {
OneSignal.push(() => {
console.log('Register For Push');
OneSignal.push(['registerForPushNotifications'])
OneSignal.on('subscriptionChange', (isSubscribed) => {
console.log('The user\'s subscription state is now:', isSubscribed);
this.listenForNotification();
OneSignal.getUserId().then((userId) => {
console.log('User ID is', userId);
this.oneSignalId = userId;
this.updateLocalUserProfile();
});
});
});
}
listenForNotification() {
console.log('Initalize Listener');
OneSignal.on('notificationDisplay', (event) => {
console.log('OneSignal notification displayed:', event);
this.listenForNotification();
});
}
getUserID() {
OneSignal.getUserId().then((userId) => {
console.log('User ID is', userId);
this.oneSignalId = userId;
});
}
checkIfSubscribed() {
OneSignal.push(() => {
/* These examples are all valid */
OneSignal.isPushNotificationsEnabled((isEnabled) => {
if (isEnabled) {
console.log('Push notifications are enabled!');
this.getUserID();
} else {
console.log('Push notifications are not enabled yet.');
this.subscribe();
}
}, (error) => {
console.log('Push permission not granted');
});
});
}
updateLocalUserProfile() {
// Store OneSignal ID in your server for sending push notificatios.
}
}
@bytelabsco
Copy link

Do you happen to have your local storage decorator available? Looks pretty useful.

@tsadkan
Copy link

tsadkan commented Dec 4, 2018

It would be so helpful if you made your local storage decorator available? Thank you.

@bytelabsco
Copy link

@tsadkan I did a little searching, and it looks like ngx-store does something very similar

@Misiu
Copy link

Misiu commented Jan 4, 2019

@PsyGik any chance You can share Your @Cache decorator?

@luisfprj
Copy link

luisfprj commented Feb 6, 2019

I would love to see more of your code, like the decorator, cause it dind't working for me.

@MSakamaki
Copy link

If pool indicates the key of localStorage, we expect the following code.
( oneSignalInit will need to be set externally to true if OneSignalService.init() succeeds )

// ../utils/storage.provider.ts
const readLocalStorageObject = (storeKey: string ): Object => {
  return JSON.parse(window.localStorage.getItem(storeKey) || '{}');
};

export function Cache({ pool }: { pool: string }) {
  return (target: any, key: string) => {
    Object.defineProperty(target, key, {
      get: () => readLocalStorageObject(pool)[key],
      set: (value: string) => window.localStorage.setItem(pool, JSON.stringify({
        ...readLocalStorageObject(pool),
        [key]: value
      })),
    });
  };
}

I also hope that @PsyGik will give me a complete answer.

@bacskaiz
Copy link

Hi,
Thanks for jour examples! We have tried the code and it works very well, excepting the listenForNotification(), that not displays anything.
Have you any idea what would be wrong?

@alexandrualin1
Copy link

Hi,
Thanks for jour examples! We have tried the code and it works very well, excepting the listenForNotification(), that not displays anything.
Have you any idea what would be wrong?

same here, any idea how to solve that?

@Sina7312
Copy link

Sina7312 commented May 14, 2019

Looks like add script dynamically invokes some problems. I added the script to my head manually, and the problems solved!

@edmilsonlani
Copy link

Any sample project using this service? I can not make it work.

@markloreto
Copy link

Hi,
Thanks for jour examples! We have tried the code and it works very well, excepting the listenForNotification(), that not displays anything.
Have you any idea what would be wrong?

yeah, does not Listen from the Notification

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment