Angular swPush.requestSubscription is not returning anything on First Call

2.1k views Asked by At

I am using swPush in my angular project. In that, the event of this.swPush.requestSubscription() is getting called by clicking a button.

For Example:

this getdeviceToken will call

getDeviceToken(): Promise<any> {
        console.log('getting device token')
        return new Promise(async (resolve, reject) => {
                if (this.swPush.isEnabled) {
                    console.log('before subscription')
                    let sub = await this.swPush.requestSubscription({
                        serverPublicKey: this.VAPID_PUBLIC_KEY
                    })
                    console.log('temp --------', sub)
                    if(sub) {
                        this.device_token = sub;
                        if(sub) {
                            console.log('if sub')
                            resolve(this.device_token);
                        }else{
                            console.log('else sub')
                            reject({ message: "Error getting device id"});
                        }
                    } else{
                        reject({ message: "Error getting device id"});
                    }
                } else{
                    console.log('sw is not enabled');
                    reject({ message: "Error getting device id"});
                }
    }

After hard reload, when I click the button for the first time it is getting stuck on the
console.log('before subscription')

and returns nothing. It makes my app unusable since the function not returning anything not even an error. So I cannot move forward.

But when I do a simple reload and click the button again it works and this.swPush.requestSubscription() returns me a promise so my app is moving forward. Anyone know Why it is not working for the first time ? Or any suggestions to improve this.

1

There are 1 answers

0
Pratik Agarwal On

I got this solution working, IDK how but it worked everytime...

  1. Set push-notification permission to Ask(default) in the page

  2. Ask for permission from user using Notification.requestPermission().then( result => { getSubscriptionData(); });

  3. avoid using chrome as it checks for security, data coming from any server except https:// are blocked. Use updated EDGE or firefox instead

please comment out any other solution if you have... here's my full code:

constructor(private _floatNotifications: FloatNotificationService,
    private readonly _swPush: SwPush,
    private _apiService: APIservice) { }

  ngOnInit(): void {
    this.getSubscription();
  }

  getSubscription() {
    console.log(Notification.permission);
    if(Notification.permission === 'default') {
      Notification.requestPermission().then(() => {
        this.requestSubscription();
      }).catch(() => {
        // show permission denied error
      });
    }
    else if(Notification.permission === 'denied') {
      // show permission is denied, please allow it error
    } else {
      this.requestSubscription();
    }
  }

  async requestSubscription() {
    try {
      const sub = await this._swPush.requestSubscription({ serverPublicKey: ServiceKeysEnum.PUSH_SUBSCRIPTION_PUBLIC_KEY });
      console.log("subscription object ", sub);
    } catch  (e) {
      this._floatNotifications.makeToast.next({header: "Task failed", text: "failed to get subscription object"+e, DurationsEnum: DurationsEnum.MEDIUM, type: "danger"});
    }
  }