angular2数据绑定不起作用?

hu山·加德卡

所以我试图将record变量传递给其他组件。

我已经使用以下代码读取了json数据,http provider并成功将其存储在变量名称record中。在组件模板中访问此对象时遇到问题。IE

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]

有什么建议么?提前致谢

像素位

http调用是异步的。之所以可能收到未定义的引用错误,是因为在http调用有机会返回之前就渲染了模板。

尝试这样做:

{{record?.name }}  

这样可以确保如果未定义记录,则不会产生错误。当http调用最终返回并为record分配了一个值时,将重新计算该表达式以显示预期结果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章