【问题标题】:I can't get my locally stored variable value in my Angular 2我无法在 Angular 2 中获取本地存储的变量值
【发布时间】:2017-11-03 11:30:07
【问题描述】:

我花了好几个小时试图找出我的代码出了什么问题。 详情如下。 在 test.ts 中进行表单验证之后,似乎很难访问最初存储的本地值。

test.html

     ...
    <form [formGroup]="AddBankForm">
              ...
    </form>
        <!--step 1 -->
        <button (click)="storeKey('500')">Store It</button>

        <!--step 2 -->
        <button (click)="checkAccountKey()">Check It</button>
      ....

test.ts

  @Component({
   selector: 'test',
   templateUrl: 'test.html'
  })
  export class TestPage {

   constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public formBuilder: FormBuilder
    ) {}

  ....
    //------------------
 public AddBankForm = this.formBuilder.group({
   bank: ["", Validators.required],
   acname: ["", Validators.required],
   acno: ["", Validators.required],
   title: ["", Validators.required]
  });
  ...
  editAccountkey: string;

  storeKey(accountid: string) {

    this.editAccountkey = accountid;
  }

  ....

  checkAccountKey() {

    if (this.AddBankForm.valid) {
    alert("My key is "+ this.editAccountkey);
    }
  }
  ....
 }

我的警报() 结果=我的关键是 ....但 预期结果 = 我的密钥是 500

【问题讨论】:

  • 你能用 plunker 重现这个问题吗?
  • 你是如何设置你的项目的?你是在移动设备上测试吗? (ionic2 标签)我从未使用过 ionic2,但也许这就是为什么?

标签: html angular typescript ionic2


【解决方案1】:

这是因为您尚未初始化 editAccountkey 变量。 editAccountkey 变量的默认值未定义。

因此,当您单击第一个按钮,然后单击第二个按钮时,它将显示正确的结果。但是如果你直接点击第二个按钮,它不会显示任何editAccountkey 的值

在这种情况下,您应该初始化editAccountkey 变量,如下所示:

public editAccountkey: string = '555';

或者你可能给它分配了一个空值。

【讨论】:

  • 按钮的定位方式是,您必须先单击“存储”按钮,然后再单击“检查”按钮。这就是为什么我将它们评论为步骤 1 和步骤 2。所以步骤 1 初始化变量。
  • 您可能在其他地方更新了 editAccountkey 的值。或者您可能在为 editAccountkey 赋值之前在 storeKey 函数中遇到了异常
  • 我刚刚尝试在 'if' 语句之前访问变量,它工作正常。但在 if 语句中它只是不可用
  • 哦,是的...我只是想通了。我在请求之前错误地将它分配给了一个空字符串。呼...非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 2017-02-16
  • 2019-08-30
  • 2017-08-04
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多