I am encountering an unspecified variable error in Ionic and I cannot determine the cause

I'm attempting to perform encryption and decryption of a basic text in Ionic. Below is the code snippet I am using:

encryptedData : any;

encryptData(data){
  this.aes
      .encrypt(this.secureKey, this.secureIV, data)
      .then(res => {
        console.log("Encrypted Data: " + res);
        this.encryptedData = res;
      })
      .catch(err => {
        console.log("Error encrypting data: " + err);
      });
 }

The input data consists of plain text which seems to be successfully encrypted based on the logged output:

https://i.sstatic.net/Y7oIu.png

However, the variable encryptedData remains null even after assigning it the (res) data. What could possibly be causing this issue?

Answer №1

Explore the fascinating realm of "this" in JavaScript.

Arrow functions have a special connection to the execution context - in this case, they are tied to a specific "this" that originates from Promise internals.

If you want to ensure the correct calling context, you can use a regular function along with "bind(...)".

Check out this example below.

Promise
      .resolve("new value")
      .then((res) => {
        this.myProp = res;
      });

The above code will not work, while this one will:

Promise
    .resolve("new value")
    .then(function(res){
        this.myProp = res;
    }.bind(this));

For an illustration of this issue, refer to this jsfiddle link (remember to open the browser's devtools for console output) https://jsfiddle.net/mg7pjLz0/4/

Answer №2

Upon closer examination, it appears that encrypt() is returning a Promise. In this scenario, it is crucial to only access the return value within the 'then' block. To verify if the encrypted data has been successfully assigned, consider adding console.log("Encrypted Data Assigned?: " + this.encryptedData); immediately after the assignment. If you see the value printed, it could indicate that you are attempting to use the value prior to the asynchronous function completing its task.

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 link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

Unlock the power of location services with Google Maps API by seamlessly converting JSON

I am experiencing difficulties with displaying markers on my Google Maps API V3 map. Below is my JavaScript code: function getMap(zoom, center) { var myOptions = { zoom: zoom, center: center, mapTypeId: google.maps.MapTypeId.ROADMAP }; var ma ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

Adjust the timing of observable delays on the fly using rxjs

Currently, I have a service which requests data and returns an Observable. To continuously replay this request after a delay time, I am utilizing the repeatWhen method as shown below: this.delay = 2000; var observ = this.myService.getData() .r ...

The output of JSTree's data.rslt.obj.text() function is an array of text values, not just the text from the specified node

I am facing an issue with the jstree where it is returning a concatenated list of node names when I try to rename a node, instead of just the text for the node I am renaming. The jstree is set up to load on demand. How can I ensure that only the text for ...

What is the method for extending props from React.HTMLProps<HTMLButtonElement>?

"react": "^17.0.2", "typescript": "^4.2.4" Can someone help me understand how to extend props from React.HTMLProps? import { FC, HTMLProps } from 'react' export interface SliderButtonProps extends HTMLPro ...

Eliminate HTML tags when CKEDITOR is switched

I recently switched from a normal textarea to CKEDITOR, with a toggle button that allows users to switch between the two. However, I encountered an issue where HTML tags are not removed after destroying CKEDITOR if there was existing content in it when swi ...

Using Chrome.downloads.download within a Chrome application

My app is running into an issue where Chrome is giving me the error message that chrome.downloads is undefined. In my attempt to download an image, here is a simple example provided... Here is the manifest: { "manifest_version": 2, "name": "Download ...

Transmit information from an IONIC 3 application to a PHP server using the POST method

Having trouble sending data from Ionic 3 to php via the http library using post? When php tries to retrieve it, it's unable to locate. Below is the Typescript file that generates the token to be sent to php and calls the php file on localhost (xampp) ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

how to change visibility with Javascript

As I work on creating a menu using HTML and JavaScript, I've designed it to be a grid layout with 3 rows and 2 columns. The menu contents are also structured in a grid format. When the screen width is reduced, the layout changes to a single row and co ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

Using AngularJS to Trigger a Click Event on an Element

Within the ng-view, a partial is being inserted containing the relevant code snippet below: <tr ng-repeat="group in groups"> <td><a href="" class="restaurant-group-edit" create-link>{{ group.name }}</a></td> <td> ...

JavaScript code for displaying and concealing elements

I have a simple requirement where I need to check for a variable and display or hide a class based on its value. This is being done on a SharePoint publishing page. The snippet below is not working as expected: if (source === 'show') { $(&a ...

The UI-Grid feature in Angular, when set to right-to-left (RTL) mode, incorrectly displays data in the opposite order compared to the

In my _Layout.cshtml file, I have a CSS that sets all UI controls to right-to-left direction using the following code: * { direction: rtl; } Currently, I am working with Angular's UI-Grid, and in RTL Localization, the ...

Model Field Serialization in Angular HttpClient

Is there a way to designate the serialized name (similar to @SerializedName in Gson) of a field in a model class when receiving JSON responses from a server? For example, if the server response includes fields like start_date or some_date, but I want my m ...

Different Ways to Modify the Appearance of Angular's mat-slide-toggle and mat-checkbox

I am facing an issue in my Angular form where I have a select box containing objects derived from database records. The goal is to automatically populate the form with the object values once one is selected. My Angular application includes an array of obj ...

Use jQuery to transition the "position:absolute" element from top to bottom and create a smooth fade effect

When the "anim" class is activated, it should smoothly fade in from top to bottom Here is the corresponding HTML code: <div class="col-xs-6" style="position:relative;"> <img src="<?= site_url('assets/image/right_bg.png'); ?>" ...

How to adjust the width of nested divs in Nuxt.js/Vue.js to align with a specific container in the stack

Is there a way to handle varying image widths in Nuxt without compromising the layout? I have an image component that needs to adjust for different screen sizes, and I want the title and description to always match the width of the image. Here's what ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' https://i.sstatic.net/3KRMQ.png The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to ...