2017-06-06 88 views
1

我想從本地json文件中讀取一些測試數據並將正確格式的數據輸出到textarea中。現在儘管它只是輸出[object Object]。我將如何去得到它,所以它輸出:角從json讀取數據到textarea

編號:theIdGoesHere

標題:theTitleGoesHere

step.service.ts用來調用JSON數據

public getJson(): Observable<any>{ 
    return this.http.get('/assets/jsonData/MyJson.json') 
     .map(response => response.json()); 
    } 

MyJson服務.json

{ 
    "data":[ 
     { 
      "id": 1, 
      "title":"Test1" 
     }, 
     { 
      "id": 2, 
      "title":"Test2" 
     } 
    ] 
} 

main.componenet.ts

private testVar: any; 
test(){ 
    this.stepService.getJson().subscribe(data => (this.testVar = data)); 
    } 

anothermethod(){ 
    this.test(); 
    this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText" 
} 

get mainStepText2() { //Rebinded this one 
    const text = []; 
    const { data } = this.testVar; 

    for (let item of this.testVar.data) { 
     Object.keys(item).forEach(key => { 
     text.push(key + ': ' + item[key]); 
     }); 
    } 

    return text.join('\r\n'); // \r\n is the line break 
    } 

回答

3

你可以遍歷你的json.data和它們的鍵來提取文本和值,並生成你需要的文本區域的字符串。

const text = []; 

    for (let item of this.textVar.data) { 
     Object.keys(item).forEach(key => { 
     text.push(key + ': ' + item[key]); 
     }); 
    } 

    return text.join('\r\n'); // \r\n is the line break 

這裏是正在運行的代碼,我把它放在app.ts:http://plnkr.co/edit/3AbQYQOW0MVBqO91X9qi?p=preview

希望這是幫助。

+0

我似乎遇到了const {data}行的問題。 ERROR TypeError:無法讀取未定義的屬性'data' – John

+0

在您的真實代碼中,只有在服務從文件中讀取json時纔會定義它。您可以將它初始化爲{},或者只是在解構中回退 'const {data = []} = this.json || {};' 並更改for line以使用'for(let item of data){',這應該這樣做。 這裏:http://plnkr.co/edit/m3pNIHLm0Shg2sDpRApZ?p=info,json有一個未定義的值,解構後的數據會回落到[]。你可以通過不同的方式來解決它。 我會推薦,初始化它:http://plnkr.co/edit/gRo6Q3mECJ3rOZi9T9kh?p=preview – Juan

2

您可以使用json管你的對象格式化爲json字符串:

[(ngModel)]="mainStepText | json" 

如果你想顯示你的對象的特定屬性,你可以在你的模板訪問:

[(ngModel)]="mainStepText.data[0].title" 

這將在您的字段中顯示「Test1」。