Ionic 3 Local Notification spamming a particular page with excessive pushes

Recently starting out with Ionic, I encountered an issue while developing a basic app that should display a specific page by opening a Local Notification. The problem arises when I create multiple notifications – after clicking on the second notification, the app ends up pushing the new page multiple times, regardless of navigating back to the root page.

I would appreciate any help or insights into what might be causing this behavior.

Below is the code for the root page:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LocalNotifications } from '@ionic-native/local-notifications';
import { Platform } from 'ionic-angular';
import { Page2Page } from '../page2/page2';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, private localNotifications: LocalNotifications, public platform: Platform) {
  }

  click() {
    this.platform.ready().then(() => {
      this.localNotifications.schedule({
        id: 1,
        title: 'Notifica',
        text: 'Single LocalNotification',
      })

      this.localNotifications.on('click').subscribe(() => {
        console.log("Notification Subscribed")
        this.navCtrl.push(Page2Page);
      })
    })
  }
}

And here is the simple second page:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-page2',
  templateUrl: 'page2.html',
})
export class Page2Page {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Page2Page');
  }
}

Answer №1

Successfully resolved the issue by subscribing to the platform only once. It is crucial to check if the platform is ready before initializing Cordova to prevent errors that could render the app non-functional.

Below is the updated code snippet:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LocalNotifications } from '@ionic-native/local-notifications';
import { Platform } from 'ionic-angular';
import { Page2Page } from '../page2/page2';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,
    private localNotifications: LocalNotifications,
    public platform: Platform) {

      this.platform.ready().then(() => {
        this.localNotifications.on('click').subscribe(() => {
          console.log("Notification Subscribed");
          this.navCtrl.push(Page2Page);
        });
      });

  }

  click(){
      this.platform.ready().then(() => {
        this.localNotifications.schedule({
          id: 1 ,
          title: 'Notifica',
          text: 'Single ILocalNotification',
        });
      });
  }
}

Answer №2

Every time you click, you are subscribing to an event. This means that with each click, a new subscription is added without overriding the previous one. To avoid this, you should either remove the old subscription before adding a new one or refrain from subscribing on every click. The following code snippet demonstrates this concept:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LocalNotifications } from '@ionic-native/local-notifications';
import { Platform } from 'ionic-angular';
import { Page2Page } from '../page2/page2';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  
  constructor(public navCtrl: NavController, private localNotifications: LocalNotifications, public platform: Platform) {
    this.localNotifications.on('click').subscribe(()=>{
      console.log("Notification Subscribed")
      this.navCtrl.push(Page2Page);
    })
  }

  click(){
    this.platform.ready().then(()=>{
      this.localNotifications.schedule({
        id: 1 ,
        title: 'Notifica',
        text: 'Single ILocalNotification',
      })
    })
  }
}

In this revised version, the subscription for localNotifications has been moved to the constructor for better management.

Answer №3

You have the power to make it happen, and it works wonderfully.

      executeNotificationTask(details: any) {
        // Set up a local notification
        this.localNotifications.schedule(details);
        // Listen for onClick event
        let subscription = this.localNotifications.on('click').subscribe((info) => {
          this.navCtrl.push(NewPage);
          // Stop listening for OnClick event after navigating to new page
          subscription.unsubscribe();
        });
      }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module 'AppModule' is throwing an error with the import of 'MatDialogRef' which is causing unexpected value. To resolve this issue, make sure to include a @

I am currently facing an issue while trying to incorporate Angular Material into my Angular project. Despite successful compilation of the program, I encounter an error when running it in the browser. Uncaught Error: Unexpected value 'MatDialogRef&ap ...

The Material UI Grid is not compatible with the Chrome DevTools Device Toolbar and may not function properly

Using MUI v5 with React and Typescript has been an interesting experience for me. When I utilize the Grid system, I set options like xs sm md lg to define item width. Interestingly, setting just xs or sm works fine, but when I include md, other options su ...

Ways to incorporate padding into md-card using Angular 2 material

Need assistance with adding padding to md-card in angular2 material. I am using md-card to display my product list but struggling to add padding on them. Here's what I have tried: product.component.html : <p> Product List </p> <div ...

How to fetch a file from a Spring Boot server using Angular 4

I'm currently developing a Spring Boot server with an Angular 4 front-end. I've created a service that allows users to download a .zip file from the front-end using HttpClient. Below is my code: Angular service: getZip(fileName: string) : Obser ...

Move to the top of the page when the next action is activated

I am working with an Angular 8 application. Within the application, I have implemented navigation buttons for next and previous actions. My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page ...

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

Iterating over an array in a TypeScript script

One of my components has a service that returns data in Json format. export interface ILocations { LocationID: string; LocationName: string; } This is the service method: getUserLocations(UserID: string):Observable<ILocations[]> { re ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

A guide to implementing typescript with Next.js getStaticProps

I have Next.js set up with the TypeScript feature enabled Currently, I am attempting to utilize the getStaticProps function following the guidelines outlined here: https://nextjs.org/docs/basic-features/typescript Utilizing the GetStaticProps type export ...

I'm encountering an Unsupported platform error for Angular installation when using [email protected] Does anyone know how to troubleshoot this issue?

C:\Users\vivek>npm install -g @angular/cli C:\Users\vivek\AppData\Roaming\npm\ng -> C:\Users\vivek\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng np ...

Steps for resetting the ng-multiselect-dropdown

Is it necessary to wrap the ng-multiselect-dropdown in a form in order to reset it? code - app.component.html <div> <p id = "node">Select a Root API Object - </p> <p style="width:50%"> <ng-multiselect-dropdown [placeho ...

Creating a star-based rating feature through directive implementation

Can anyone help me figure out why my static star rating system using angularjs/ionic is not showing up on the screen? I've been struggling with it and would appreciate some guidance. service.html <ion-list> <ion-item ng-repeat="busine ...

Creating a stepper module in Angular 6

Looking for assistance from Angular experts app.component.html <app-stepper [activeStep]="0"> <app-step [sid]="0"> <div>iam step 1</div> </app-step> <app-step [sid]="1"> <div>iam step 1& ...

The designated apiUser.json file could not be located within the _http.get() function

It's puzzling why my URL isn't working in _http.get('app/api/apiUsers') for Angular version 4.0.0, when it functions correctly in Angular version 2.3.1. The code is identical in both Angular versions: import { Injectable } from ' ...

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

Guide to generating TypeScript output files within a non-hierarchical directory layout

In my project, I have a directory structure with multiple typescript files organized as follows: | src | app-1 | tsconfig.json | app-2 | tsconfig.json | common | standalone | tsconfig.json For each of the ...

HttpErrorResponse: unexpected internal server error

Just getting started with Angular 6. I created a post service using Spring Boot, and it works perfectly when tested with Postman. But testing it in a web browser results in the following error: HttpErrorResponse {headers: HttpHeaders, status: 500, statusT ...

Effortless Registration and Authentication using Ionic with Firebase

Recently, I embarked on my journey to learn Ionic. I'm seeking some guidance on how to incorporate Login and Sign-up features using Firebase in Ionic. Any assistance would be greatly appreciated! ...

Encountered an error: Object(...) does not conform to function standards in the handleChange method

When using JavaScript, everything works fine. However, when trying to implement TypeScript with the handleChange function, an error is consistently thrown whenever something is typed into the entries. The error message reads: "TypeError not captured: Objec ...

Angular's POST request to Web.API was blocked due to cross-origin restrictions

A demonstration application is being developed at a small scale: Frontend using Angular (http://localhost:4200/) Backend using ASP.Net Core (https://localhost:44333/) Currently, the GET requests from frontend to backend are functioning correctly. Howeve ...