Angular中无法用*ngFor插值显示数组blank的问题求助
问题解决:Angular模板无法显示
blank数组 核心原因
你在HTTP请求的subscribe回调里用var blank = new Array()定义的是局部变量,只能在当前回调函数内部访问,Angular模板(HTML)无法直接读取组件的局部变量,必须把blank声明为组件的类成员属性。
具体修复步骤
- 在组件类中声明
blank属性
在组件类的顶层(比如export class YourComponent implements OnInit { ... }内部)添加:
blank: any[] = []; // 初始化空数组,避免模板读取时出现undefined报错
- 修改subscribe内的代码
删掉原来的var blank = new Array();,直接使用组件类的this.blank:
this.http.get(this.datajson).subscribe(sort_data => { this.allData = [sort_data as any]; // 直接操作组件的blank属性,无需重新定义局部变量 const foundItem = sort_data.country.state[0].city[0].borough.neighborhood.street.find(isCherries); if (foundItem) { // 避免push undefined导致的后续问题 this.blank.push(foundItem); } console.log(this.blank); // 调试时也用组件属性 });
- 模板中正常使用
*ngFor和插值表达式
HTML里可以这样写:
<!-- 遍历blank数组显示内容 --> <div *ngFor="let item of blank"> {{ item.id }} <!-- 根据你的数据结构调整显示的属性 --> </div> <!-- 调试用:直接打印数组的JSON结构 --> <p>{{ blank | json }}</p>
额外优化建议
- 不要用
var,改用const/let,符合TypeScript/JavaScript的最佳实践 - 代码里的
all_data数组是冗余的,直接用sort_data即可,没必要额外创建 - 你代码里
all_data[0].country.state[1].city[0].borough.neighborhood.street.find(isCherries).find();这一行会报错:find()返回单个对象而非数组,不能链式调用find(),建议删掉或修正
内容的提问来源于stack exchange,提问作者allforthenoob
相关产品推荐
相关产品推荐

