简体   繁体   English

我在Ionic中得到一个未定义的变量,我不确定为什么吗?

[英]I'mg getting an undefined variable in Ionic and I'm not sure why?

I'm trying to encrypt and decrypt a simple text in Ionic. 我正在尝试加密和解密Ionic中的简单文本。 Here's my code: 这是我的代码:

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 data is a simple plain text and it gets encrypted as I can see from the logs: 数据是简单的纯文本,并且从日志中可以看到它被加密了:

在此处输入图片说明

However the variable encryptedData comes as null after setting the (res) data to it. 但是,在将变量(res)设置为变量后,变量encryptedData变为空。 What could I be doing wrong? 我可能做错了什么?

Welcome to the world of "this" in JavaScript. 欢迎来到JavaScript中的“ this”世界。

Arrow functions are bound to the execution context - in this example, it will be invoked with some kind of "this" that comes from Promise internals. 箭头函数绑定到执行上下文-在此示例中,将使用Promise内部提供的某种“ this”来调用它。

You can enforce calling context by using regular function combined with "bind(...)". 您可以通过将常规函数与“ bind(...)”结合使用来强制调用上下文。

Please, take a look at the following example. 请看下面的例子。

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

Will not work, but this: 将不起作用,但这是:

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

will. 将。

Take a look at this jsfiddle which reproduces your problem (open browser's devtools to see console output) https://jsfiddle.net/mg7pjLz0/4/ 看看这个jsfiddle,它再现了您的问题(打开浏览器的devtools以查看控制台输出) https://jsfiddle.net/mg7pjLz0/4/

It looks like encrypt() returns a Promise; 看起来crypto()返回一个Promise; in such a case, you are only able to use the return value inside the 'then' block. 在这种情况下,您只能使用'then'块内的返回值。 You should check, perhaps by doing console.log("Encrypted Data Assigned?: " + this.encryptedData); 您应该通过console.log(“ Encrypted Data Assigned ?:” + this.encryptedData);进行检查。 right after you assignment if the value gets assigned. 如果分配了值,则在分配后立即执行。 If the value is printed, then maybe you are trying to use the value before the async function returns. 如果已打印该值,则可能您正在尝试在异步函数返回之前使用该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM