Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度2:未定义self.context.data.style_Javascript_Json_Angular - Fatal编程技术网

Javascript 角度2:未定义self.context.data.style

Javascript 角度2:未定义self.context.data.style,javascript,json,angular,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的模板

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

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

你的
自我。上下文
错误在这里:

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建议您可能必须使用安全的操作员一样。

您是否尝试过使用安全的导航操作员?像这样:
ui?.colors?.first
它应该是
[ngStyle]
而不是
[ngStyle]
。它应该是
ui.style.colors.first
@romac不,她(我假设)已经声明了
this.ui=this.data.style在她的订阅中:)我尝试了安全导航操作员,它工作得非常好。什么是安全操作员?他们是干什么的?我以前从未听说过它们。@LadyT它们基本上是
if
检查对象是否为
null
未定义的
@echonax感谢您的澄清。
this.dataService.getData()
 .subscribe(
    data => {
     this.data = data;
     this.ui = this.data.style;
    },
    err => console.error(err),
    () => console.log('Data loaded')
 );