【发布时间】: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