Unable to get AlertController to function properly within FCMPlugin in Ionic 2

Trying to implement an alert using AlertController within an Ionic app inside the FCMPlugin.onNotification() function, but encountering issues where the alert controller is not being created. It seems that the method halts execution after the code for creating the alert.


pushNoteSetup(){
if(typeof(FCMPlugin) !== "undefined"){
  FCMPlugin.getToken(function(t){
    console.log("Use this token for sending device specific messages\nToken: " + t);

  }, function(e){
    console.log("Uh-Oh!\n"+e);
  });

  this.confirmAlert('Hi');

  FCMPlugin.onNotification(
    function(d){
      if(d.wasTapped){
        // Background receival (Even if app is closed),
        //   bring up the message in UI
        let message = d['aps']['alert'];
        console.log('Message received: ' + message);
         this.alert = this.alertCtrl.create({
          title: 'Hi',
          message: 'Boo',
          buttons: ['Ok']
        });
        this.alert.present();
        console.log('Should have displayed an alert');
        this.confirmAlert(message);
        console.log('Skipping over alers?');
      } else {
        let message = d['aps']['alert'];
        console.log('Message received: ' + message);
        let alert = this.alertCtrl.create({
          title: 'Hi',
          message: 'Boo',
          buttons: ['Ok']
        });
        alert.present();
        console.log('Should have displayed an alert');
        this.confirmAlert(message);
        console.log('Skipping over alers?');
        this.confirmAlert(message);
      }
    }, function(msg){
      // No problemo, registered callback
      console.log('Message:' + msg);
    }, function(err){
      console.log("Arf, no good mate... " + err);
    });
  } else {

    console.log("Notifications disabled, only provided in Android/iOS environment");
  }
}
public confirmAlert(message: any){
let mesg = String(message);

console.log('Message to display '  + mesg + ' and ' + message);

let confirmAlert = this.alertCtrl.create({
       title: 'Alert',
       message: message,
       buttons: [{
         text: 'Cancel',
         role: 'cancel',
         handler: () => {
           console.log('cancel');
         }
       }, {
         text: 'Confirm',
         handler: () => {
           console.log('Confirm');
         }
       }]
     });
     confirmAlert.present();

}

This function is invoked after platform.ready() in app.componenet.ts

Answer №1

Your implementation includes a JavaScript function that alters the value of this, causing it to reference the function context. To address this, you may consider preserving the context by assigning it to a variable called self:

self = this;

Later in the callback function:

   function(d){
      if(d.wasTapped){
        // When receiving notifications in the background (even when the app is closed),
        // display the message on the UI
        let message = d['aps']['alert'];
        console.log('Received Message: ' + message);
         self.alert = self.alertCtrl.create({
          title: 'Hello',
          message: 'Boo',
          buttons: ['Ok']
        });
        self.alert.present();
        //...

An alternative approach would be to utilize arrow functions:

FCMPlugin.onNotification(
   (d)=>{
   //create alert
   });

Answer №2

Suraj mentioned that you are using javascript.

Here is an alternative code snippet for you to try:

if(typeof(FCMPlugin) !== "undefined"){ 


FCMPlugin.getToken(
                 (token)=>{
                    console.log(token);
                },
                 (err)=>{
                    console.log('error retrieving token: ' + err);
                }
            );  



    FCMPlugin.onNotification(
         (data)=>{
            if(data.wasTapped){
                //Notification was received on device tray and tapped by the user.
                //Do something
            }else{
                //Notification was received in foreground. Maybe the user needs to be notified.
              this.alertBox = this.alertCtrl.create({
              title: data.title,
              subTitle: data.body,
              buttons: [{
                text: 'Cancel',
                role: 'cancel',
                handler: () => {
                console.log('cancel');
                }
              }, {
                  text: 'Confirm',
                  handler: () => {
                  console.log('Confirm');
                  }
                 }]
              });     
              this.alertBox.present();                  
            }
        },
         (msg)=>{
            console.log('onNotification callback successfully registered: ' + msg);
        },
         (err)=>{
            console.log('Error registering onNotification callback: ' + err);
        }
    );
 } 
else console.log("Notifications disabled, only provided in Android/iOS environment");

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

Tips for configuring VS Code to automatically change a callable property to an arrow function instead of a standard function

When interacting with ts/tsx files in VS Code, the autocompletion feature for callable properties offers two options: propertyName and propertyName(args): https://i.sstatic.net/BFVTm.png However, selecting the second option generates a standard function: ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Issue: Unable to find solutions for all parameters in (?, ?)

Below is the unit test I've written for my Angular 10 component, which showcases a tree view with interactive features: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/for ...

Adding Custom CSS File to an iFrame in Angular

Currently, I am attempting to include a CSS file in a third-party iframe to modify its styling. My initial idea was to employ the following code snippet: ngOnInit() { ... this.myIframe.nativeElement.document.head.appendChild('style.css') } U ...

I need to print out a table, but when I preview the print, I want to rotate the entire page for better visibility

Is there a way to rotate the print review using CSS and HTML? I am facing issues as the CSS styles do not seem to apply properly on it. Can someone help me solve this problem? ...

The function is attempting to access the 'lockDatabase' property of an undefined object, resulting in an error

I'm encountering an error due to the scope issue with 'this', and I'm struggling to find a solution. I attempted using the fat arrow, which solved the scope problem but created another issue where I lack a callback value that needs to b ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

The API response could not be shown at this time

My API is sending a JSON response. I'm currently attempting to display it in one of my components to better understand how the data is being transferred and displayed for future development. Despite my component functioning correctly with other conte ...

Is there a way to sort the output of an observable in various different methods?

One interesting feature I have implemented is a TableData type observable that provides me with a collection of table rows and columns. The user has the option to select a set of columns from a dropdown menu (which corresponds to the rows) to be sorted in ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

How to Resolve Angular 2 Reactive Forms Problem the Angular Native Approach, not using jQuery

Utilizing Angular 2 Reactive Forms alongside Typescript, my template structure is as follows: <form [formGroup]="form"> <div class="M"> <div class="X"> <!-- I would like to avoid adding (change)="onChanged()" o ...

What is the best way to exclude React.js source files from a fresh Nest.js setup?

My setup includes a fresh Nest.js installation and a directory named "client" with a clean create-react-app installation inside. Here is the project structure: ./ ...some Nest.js folders... client <- React.js resides here ...some more Nest.js fo ...

BrowserRouter - The type '{ children: Element; }' is not compatible with the type 'IntrinsicAttributes', as they do not share any properties in common

After upgrading to React version 18, I encountered a type error with the BrowserRouter component. Despite trying various approaches, I am unable to pinpoint the root of the problem. Here is the error that pops up during debugging: Overload 1 of 2, &a ...

Having trouble retrieving values from a feature file in a Typescript implementation with the Cucumber Framework

Having trouble accessing values from a feature file in Typescript while using the Cucumber Framework tool Protractor. How do I retrieve these Example values in my typescript method within the When block? Here is the code for the Feature file: Feature: Na ...

Creating an array of objects using Constructors in Typescript

Utilizing TypeScript for coding in Angular2, I am dealing with this object: export class Vehicle{ name: String; door: { position: String; id: Number; }; } To initialize the object, I have followed these steps: constructor() { ...

Extracting JSON information in Node.js

I am working with data retrieved from Firebase that appears to be in JSON format. I need assistance extracting the value for 'ordered_item_cost' and other data fields from this dataset. Here is a snippet of the data: { '-LaAHp3jEK70tWB01-G ...

Determining the Best Option: React JS vs Angular UI Framework

After researching the latest versions of React and Angular online, I discovered that both are suitable for developing Web Application UI. However, I also realized that there are key differences to consider when choosing between the two. Let's say I h ...

New Angular Datatables used to create a revitalizing table

In my project, I am utilizing the Angular Datatables library. The data is fetched from a URL that returns a JSON object, which is then stored in an array and used to populate a table. appenditems(){ this.items = []; this.items2 = []; this.items ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...