【问题标题】:Angular 2: self.context.data.style is undefinedAngular 2:self.context.data.style 未定义
【发布时间】:2017-01-05 18:15:16
【问题描述】:

我正在使用服务加载应用程序组件上的 json 数据。

this.data = this.dataService.getData()
 .subscribe(
    data => {
     this.data = data;
     this.ui = this.data.style;
    },
    err => console.error(err),
    () => console.log('Data loaded')

 );

当我尝试在 NgStyle 的模板组件中访问 this.ui 时,我收到错误“Self.context.ui 未定义”。这很奇怪,因为它显示在控制台中,但是一旦我将它添加到我的组件中,它就吓坏了。

此代码在应用程序组件中,我正在尝试从我的 json 中获取动态样式

<h1 [NgStyle]="{'color': ui.colors.first}"> Random text </h1>

这是json结构,看起来是这样的。

{
 "style":{
   "colors": {
      "first": "#ffffff"
    }
  }
}

我真的不知道为什么 Angular 不让我使用数据,你认为这里发生了什么?

【问题讨论】:

  • 您是否尝试过使用安全导航运算符?像这样:ui?.colors?.first
  • 它也应该是[ngStyle] 而不是[NgStyle]
  • 应该是ui.style.colors.first
  • @RomanC 不,她(我想)在她的订阅中声明了this.ui = this.data.style; :)

标签: javascript json angular


【解决方案1】:

您的self.context 错误在这里:

this.data = this.dataService.getData() 

应该只是:

this.dataService.getData()
 .subscribe(
    data => {
     this.data = data;
     this.ui = this.data.style;
    },
    err => console.error(err),
    () => console.log('Data loaded')
 );

您将数据分配给this.data 内部的this.data,这就是它抱怨self.context 的原因。

[NgStyle] 应该是[ngStyle],就像@echonax 建议的那样,您可能必须使用安全运算符。

【讨论】:

  • 我尝试了安全导航操作符,它运行良好。什么是安全运算符?他们在做什么?我以前从未听说过它们。
  • @LadyT 他们基本上是if 检查对象是null 还是undefined
  • @echonax 感谢您的澄清。
猜你喜欢
  • 2017-01-28
  • 2018-02-25
  • 2021-01-20
  • 2017-01-30
  • 1970-01-01
  • 2017-01-08
  • 2019-07-28
  • 2017-07-12
  • 1970-01-01
相关资源
最近更新 更多