所以我试图将record
变量传递给其他组件。
我使用http provider
读取了json数据,并使用下面的代码成功地将其存储在变量名record
中。
我在组件模板中访问此对象时遇到问题。
即。
1.left-sidebar.component.ts
import {Component, OnInit,Input} from 'angular2/core';
import {ComponentBarComponent} from "./../component-bar/component-bar.component";
import { DataService } from '../../../app/services/data.service';
import {Http, Response} from 'angular2/http';
@Component({
selector: 'left-sidebar',
directives:[ComponentBarComponent],
providers: [DataService],
template: `
<div style="overflow-y:auto;height:62vh;">
{{record | json}} //this prints record object in json format correctly
{{record.name}} //but this line produces exception
<component-bar [record]="record"></component-bar>
//also this object is not getting passed to component-bar object.
</div>`
})
export class LeftSidebarComponent implements OnInit {
public absolutePath:string;
record:Object;
constructor(private dataService: DataService) {
this.componentName="Heading";
this.absolutePath="http://localhost:8080/src/app/lib/component-group.json";
this.dataService.getData(this.absolutePath)
.subscribe((data:any[]) => {
this.record = data;
console.log(this.record.name);//this prints component name correctly
});
}
ngOnInit() {
}
}
2.component-group.json
{
"name": "components",
"desc": "components",
"libName":"Standard",
"components": [
{
"name":"HeadingComponent",
"desc":"",
"cmpType":"Standard",
"imgUrl":"http://localhost:3202/uploads/ABC.png",
"cmpLocation":"",
"isDynamic":"true"
},
{
"name":"BodyComponent",
"desc":"",
"cmpType":"Standard",
"imgUrl":"http://localhost:3202/uploads/pqr.png",
"cmpLocation":"",
"isDynamic":"true"
},
{
"name":"FooterComponent",
"desc":"",
"cmpType":"Standard",
"imgUrl":"http://localhost:3202/uploads/erter.png",
"cmpLocation":"",
"isDynamic":"true"
}
],
"createdBy":"ABC",
"updatedBy":"ABC"
}
当我使用{{record | json}}
时,它会正确打印json数据,但是当我尝试像{{record.name}}
那样打印它时会产生以下异常
EXCEPTION: TypeError: Cannot read property 'name' of undefined in [
{{record | json}}
{{record.name }}
in LeftSidebarComponent@22:43]
有什么建议吗? 提前谢谢
答案 0 :(得分:2)
http调用是异步的。您可能收到未定义的引用错误的原因是因为在http调用有机会返回之前呈现模板。
尝试这样做:
{{record?.name }}
这确保了如果未定义记录,则不会产生错误。当http调用最终返回并为记录分配值时,将重新计算表达式以显示预期结果。