Transitioning from one provider to another and encountering the error message "Cannot read property prompt of undefined."

This is an example of an alert service in TypeScript

 public Alert = {
        prompt: () => {
          return new Promise((resolve, reject) => {
            let prompt = this.alertCtrl.create({
              title: 'Enter username',
              inputs: [
                {
                  name: 'username',
                  placeholder: 'Username'
                },
              ],
              buttons: [
                {
                  text: 'Cancel',
                  handler: data => {
                    reject(false);
                  }
                },
                {
                  text: 'Save',
                  handler: data => {
                    console.log(data);
                    resolve(data);
                  }
                }
              ]
            });
            prompt.present();
          });
        }
      }

This is how the request service uses the Alert function:

function () {
    this.prompt.Alert.prompt().then((res) => {
           this.user.username = res;
           alert(this.user.username);
    }, err => {
          this.alertService.Alert.alert('user_cancelled', 'Error');
    }); 
}

While this code works in the browser using IONIC Serve, it seems to have issues on a device. I'm encountering an error that says "Can not read property 'prompt' of undefined".

Answer №1

When you type that

function () {
    this.prompt.Alert.prompt().then((res) => {
          this.user.username = res;
          alert(this.user.username);
    }, err => {
          this.alertService.Alert.alert('user_cancelled', 'Error');
    }); 
}

If you opt not to utilize Typescript fat arrow functions, you must employ Javascript closures in order to maintain the correct context for the this keyword.

Currently, the this keyword is linked to your function rather than your object.

UPDATE Illustration of closures:

Within a typescript class :

x = 'Hey baby';
let fatArrowFunction= () => console.log(this.x); // "Hey baby"
that = this;
let usualFunction = function() {
  let x = 'Hey sweetheart';
  console.log(x); // "Hey sweethearth"
  console.log(this.x); // "Hey sweethearth"
  console.log(that.x); // "Hey baby"
}

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

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

Add a feature to a functional component that is enclosed with React.forwardRef

Within my codebase, there exists a component that is wrapped with React.forwardRef and serves as a compound component. One challenge I encountered was how to preserve the functionality of Form.Item = FormItem; while still having the Form component fun ...

Step-by-step guide for adding an object to a Material UI select component

I am in the process of incorporating a Select component with reactjs material ui and typescript. Yet, I encounter this typing error: Property 'id' does not exist on type 'string'. Property 'name' does not exist on type ' ...

The silent refresh functionality is currently not functioning as expected in Angular's OAuth OIDC implementation

In my Angular SPA, I am attempting to silently refresh the access token. The authentication with ADFS has been successfully completed and everything is functioning properly. Below is the configuration that I have implemented: oauthService.configure({ ...

Transforming the data type of a variable

Recently, I decided to switch my file name from index.js to index.ts. Here's an example of the issue I'm facing: let response = "none" let condition = true if(condition){ response = {id: 123 , data: []} } console.log(response) Howev ...

Angular component name constraints - 'the selector [your component name] is not permissible'

When trying to generate a component using the Angular 6 CLI (version 6.0.7), I encountered an issue. After typing in ng g c t1-2-3-user, I received an error message stating that the selector (app-t1-2-3-user) is invalid. I wondered if there was something ...

What causes Next.js to struggle with recognizing TypeScript code in .tsx and .ts files?

Webpages lacking a declared interface load correctly https://i.stack.imgur.com/DJZhy.png https://i.stack.imgur.com/r1XhE.png https://i.stack.imgur.com/zXLqz.png https://i.stack.imgur.com/Z1P3o.png ...

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...

Understanding the JSON data in Ionic 2

How do I extract the token from JSON data? The JSON data I have is: "{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}" I need to access the toke ...

The usage of Angular Tap is no longer recommended or supported

My Angular application contains the following HTTP interceptor: import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse } from '@angular/common/http'; ...

Having trouble getting the Bootstrap toggle checkbox to function properly within Angular 2 components?

Working on an Angular 2 project with Bootstrap, I recently tried to integrate a bootstrap-toggle checkbox into the UI. Despite following the instructions from this site, the checkbox was displayed as a normal checkbox instead of toggled. The Index.html cod ...

Webpack and incorporating bespoke scripts

Can someone please help me understand how webpack works? I'm currently working on an Angular 2 project with a webpack starter and I have some JavaScript scripts from AWS (my SDK for API Gateway). These are about 10 JS files that I currently have liste ...

Tips for showcasing an array containing two different types of objects in Angular

After sending a request to a remote server, I am returned with a JSON array. However, the array can contain two different types of JSON objects: [ { "country": "USA", "caseCount": 561, "caseDates": [], ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

Error code TS2749 is indicating that the identifier 'XXX' is being interpreted as a value instead of a type. Perhaps you intended to use 'typeof XXX' instead

I've encountered a strange issue while running my npm run dev command in my project built with Nuxt.js, which includes Vue.js components. While launching the application, I'm encountering errors related to TypeScript like TS2749: 'About&apos ...

Should the null-forgiving operator be avoided when using `useRef`?

Is the following code snippet considered poor practice? const Component: React.FC<{}> = () => { const ref = React.useRef<HTMLDivElement>(null!); return <div ref={ref} />; } I'm specifically questioning the utilization of ...

Are browser window.sessionStorage and ng libraries like ngx-webstorage considered safe to implement in Angular 4?

Seeking the optimal approach for utilizing Session Storage in Angular 4 or newer versions such as 5. The current project is making use of HTML5 window localStorage and sessionStorage. Is it advisable to implement third party libraries like angular-2-local ...

There will be no further upgrades available for Angular CLI after version 1.6.0

Based on the latest information from npm, the current version of @angular/cli is v6.2.5. Upon running ng -v, the output shows: _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ &b ...

Upon receiving data from the Api, the data cannot be assigned to the appropriate datatype within the Angular Object

I am encountering an issue with the normal input fields on my page: https://i.stack.imgur.com/qigTr.png Whenever I click on the "+" button, it triggers an action which in turn calls a service class with simple JSON data. My intention is to set selectionC ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...