javascript - Angular 2 : self. context.data.style 未定义

标签 javascript json angular

我正在使用服务加载应用程序组件上的 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/

相关文章:

angular - 如何在 GoDaddy 上托管 Angular-CLI 项目?

javascript - 创建简单的依赖 jquery 选择框不起作用

javascript - ASP.NET - 未捕获的语法错误 : Cannot use import statement outside a module

javascript - Electron-fetch将json作为[对象对象]返回,但网络控制台显示正在返回正确的json对象

node.js - 如何解决node-sass安装脚本错误

angular - ReactJs 是否有像 Angular 4.0 那样的 AOT?

javascript - 在 Angular JS 中设置远程数据变量

javascript - 通过点击按钮获取一行的id和value

json - 玩框架路由麻烦(400错误请求)

json - 还有其他方法可以针对JSON中的多个嵌套字段优化此Elasticsearch查询