0

I am trying to configure push notifications for my Angular project. I tried with the AngularFire module, but I am facing issues - https://github.com/angular/angularfire/issues/2299. So I thought of using vanilla Javascript code. So I created Javascript function which will display the Notification permission request dialog and write the token to the console. And I am able to call the function from Angular. But instead of writing the token to the console, I need to save the token in my database, so that I can associate the token to users of my application and send the notification to specific users. I couldn't find any ways to do this. Here is my Javascript function which shows the browser notification prompt and writes the token to the console.

var requestForPermission = function () {
  messaging.requestPermission().then(m => {
    messaging.getToken().then(t => {
      console.log(t);
    });
  });
}

And in typescript I created a function like this.

declare function requestForPermission(): any;

And finally calling this function from a typescript function.

toggleBrowserNotification() {
  requestForPermission();
}

I tried to return the token, messaging object etc, but I don't know how to consume these object in Typescript.

4
  • 1
    What do you mean with your database? where do you need The token? It Is not clear. Commented Apr 16, 2020 at 2:38
  • Yes, I need to store the notification token (registration id) to my application database so that I can associate it to users and send a notification to specific users. Commented Apr 16, 2020 at 2:51
  • do you have already the code in the front to save that token? Is that code in the same class that "toggleBrowserNotification"? Commented Apr 16, 2020 at 2:55
  • Problem is my code to save the token to the database is in Angular typescript. And I need to get the token from Javascript to Typescript / Angular so that I can save the token to database. Commented Apr 16, 2020 at 3:08

1 Answer 1

1

If I understood fine your problem, you can try this.

JS

var requestForPermission = async function () {
    let m = await messaging.requestPermission();
    return await messaging.getToken();
}

TS

toggleBrowserNotification() {
   requestForPermission()
       .then(t => this.myTokenSaverService.savetoken(t)) //All succesful
       .catch(e=> console.log(e)); //Error getting permission or token
}

Regards,

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.