【问题标题】:Accessing JSON object value using components input parameter使用组件输入参数访问 JSON 对象值
【发布时间】: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


【解决方案1】:

使用 Angular 输入的正确语法是:@Input() input: string(请注意,您的示例中缺少括号)。

下面是一个简单的例子:

app.component.html

&lt;app-foo bar="baz"&gt;&lt;/app-foo&gt;

bar.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.scss']
})
export class FooComponent implements OnInit {
  @Input() bar: string;

  constructor() {
    console.log('Shows undefined:', this.bar);
  }

  ngOnInit() {
    console.log('Shows baz:', this.bar);
  }
}

如果你运行它,它会在控制台中显示baz

您可以阅读有关输入的更多信息:https://angular.io/api/core/Input

【讨论】:

  • 嗨!你对@Input() 的语法是正确的,我在写我的问题时确实偷工减料。我在实际代码中使用了正确的语法。问题是需要从“/config.json”导入配置而不是从“/config.json”导入*作为配置的JSON导入我想知道这些有什么区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 2013-04-28
  • 1970-01-01
相关资源
最近更新 更多