You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular组件中跨函数访问赋值后的类成员变量显示undefined问题

解决Angular组件变量显示undefined的问题

Hey there! Let's walk through why your name1, pw, and g variables are showing up as undefined when you call ClickMe(), and how to fix it.

核心问题:执行顺序

First off, the most likely culprit is that you're clicking the ClickMe button before triggering the Save() method. Since displayAccountInfo() (which assigns values to your three variables) is only called inside Save(), those variables won't have any values until you click the Save button first.

So make sure you follow this order:

  1. Fill out your form with valid values
  2. Click the Save button to run Save() and populate name1, pw, g
  3. Then click the ClickMe button to display the saved values

修复代码中的潜在错误

Even if you fix the execution order, there's a small bug in your displayAccountInfo() method that could cause issues later (though it doesn't affect your current variable problem):

In the certificates loop, you're using the wrong index variable (i instead of j):

// 错误代码
for(var j=0; j< account.certificates.length; j++) {
  var cer=account.certificates[i]; // 这里误用了i,循环变量应为j
}

// 修复后
for(var j=0; j< account.certificates.length; j++) {
  var cer=account.certificates[j];
}

优化变量与字符串拼接

To avoid seeing undefined even if the variables haven't been assigned yet, give them initial empty values when declaring them:

name1: string = '';
pw: string = '';
g: string = '';

Also, using template literals in ClickMe() will make your string way easier to read and format:

ClickMe():void {
  this.result = `*saved dataItems: ${this.name1} ${this.pw} ${this.g}`;
}

确认模板绑定

Double-check your component's template to make sure:

  • The Save button has the click event bound: (click)="Save()"
  • The ClickMe button has the click event bound: (click)="ClickMe()"
  • You're displaying the result variable somewhere, like <p>{{ result }}</p>

Following these steps should get your saved values showing up correctly when you click ClickMe!

内容的提问来源于stack exchange,提问作者Codelover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:00:27