【发布时间】:2019-03-11 16:08:32
【问题描述】:
我是 Angular 新手,我无法理解为什么我无法使用组件输入参数作为键来访问 JSON 对象值。
在我的应用组件中,我添加了三个组件:
<app-example input="example1"></app-example>
<app-example input="example2"></app-example>
<app-example input="example3"></app-example>
组件 "app-example" 将配置 JSON 文件导入为配置并具有 @Input() 输入:字符串;
在“app-example”组件中,我尝试使用 config[this.input] 访问 ngOnInit() 中的配置
当我 console.log(config[this.input]) 打印出 undefined
当我 console.log(this.input) 它打印出输入字符串(例如“example1”)
但是,如果我例如 console.log(config["example1"]) 它会打印出相应的对象。
这可能是非常基本的东西,但我就是想不通。
【问题讨论】:
-
疯狂猜测,因为您没有发布代码。你需要
this.input,而不是input。编译器应该警告你这个错误。 -
那是我的错字。我确实使用了this.input。我刚刚发现,如果我这样导入: import config from "/config.json" 而不是 import * as config from "/config.json" 似乎可以工作。很高兴知道为什么
标签: angular