我正在使用服务加载应用程序组件上的 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 不允许我使用这些数据,你认为这里发生了什么?
最佳答案
您的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建议你可能必须使用安全运算符。
关于javascript - Angular 2 : self. context.data.style 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491939/