簡體   English   中英

angular2數據綁定不起作用?

[英]angular2 data binding not working?

所以我試圖將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}} {{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分配了一個值時,將重新計算該表達式以顯示預期結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM