简体   繁体   English

在TypeScript中,如何在本地更改全局变量的值?

[英]In TypeScript, how do I change the value of a global variable locally?

public login(username: string, password: string): string {

const options = {}; 
let flag = 1;  
this.auth0.client.login({realm: 'Username-Password-Authentication', username, password}, (err,authResult) => {
  if(err) {
    flag = 1;
    console.log(err);   
    return;
  }
  else if (authResult && authResult.accessToken && authResult.idToken) {
    let flag = 0;
    this.setSession(authResult);
    alert("Flag: " + flag);
  }
  else {  
    console.log(err); 
    return;
    //alert('Error: ${err.error_description}. Check the console for further details.'); console.log(username,password)
}
});
if(flag == 0) {
  alert(flag);
  return "Invalid credentials";
}
}

In this code block the "if(flag == 0)" statement is never executed, since the global value is 1. How do I change the global value of flag? 在此代码块中,由于全局值为1,因此从不执行“ if(flag == 0)”语句。如何更改flag的全局值?

Your main problem is that: 您的主要问题是:

this.auth0.client.login()

is asynchronous. 是异步的。 That's why you are passing it a callback function. 这就是为什么要向其传递回调函数。

What this means is that the order of operations is: 这意味着操作顺序为:

  1. let flag = 1 ; let flag = 1 ;
  2. start the async operation with this.auth0.client.login() 使用this.auth0.client.login()启动异步操作
  3. test if (flag == 0) // which of course doesn't fire because flag still equals 1 测试if (flag == 0) //当然不会触发,因为flag仍然等于1
  4. async callbacks fire and you try to set flag, but it's too late. 异步回调触发,您尝试设置标志,但是为时已晚。

You need to somehow move the logic into the async side of things. 您需要以某种方式将逻辑移到事物的异步方面。 This might require that your main login() accepts a callback that you can fire when is.auth0.client.login() is done or use a promise. 这可能需要您的主login()接受一个回调,您可以在is.auth0.client.login()完成或使用promise时is.auth0.client.login()该回调。

One way or another your if(flag == 0) {} test needs to be inside the callback. 您的if(flag == 0) {}测试必须以某种方式包含在回调中。 And you probably don't want to create a new local variable inside the else if -- I think you want flag = 0; 而且, else if -我认为您希望flag = 0;您可能不想在else if内部创建新的局部变量flag = 0; not let flag = 0; let flag = 0;

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

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