Skip to content

Instantly share code, notes, and snippets.

@PsyGik
Created November 24, 2018 06:49
Show Gist options
  • 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.
}
}
@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