2016-05-14 104 views
1

我有這樣的:顯示JSON對象模板角2

stanservice.categoryDetail(this.params.get('id')) 
    .then((data) => { 
    this.category = JSON.stringify(data.res.rows[0]); 
    console.log(JSON.stringify(data.res.rows[0])); 
    }) 
    .catch((error) => { 
    console.log("Error message", error.err); 
    }); 

控制檯日誌返回此:

{"id":6,"name":"destiny","note":"nice","type":"income"} 

然後我能在我的模板,顯示this.category就象這樣:

{{ category }} 

返回頂部

{"id":6,"name":"destiny","note":"nice","type":"income"} 

然而,當我嘗試這樣做

{{ category.name }} 

我得到這個錯誤顯示對象的值:

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: TypeError: Cannot read property 'name' of undefined in [ 
      {{ category.name }} 
     in [email protected]:18] 
ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined 
ORIGINAL STACKTRACE: 
TypeError: Cannot read property 'name' of undefined 
    at AbstractChangeDetector.ChangeDetector_CategorydetailPage_0.detectChangesInRecordsInternal (viewFactory_CategorydetailPage:67:28) 
    at AbstractChangeDetector.detectChangesInRecords (http://localhost:8100/build/js/app.bundle.js:13535:18) 
    at AbstractChangeDetector.runDetectChanges (http://localhost:8100/build/js/app.bundle.js:13512:14) 
    at AbstractChangeDetector._detectChangesInViewChildren (http://localhost:8100/build/js/app.bundle.js:13612:18) 
    at AbstractChangeDetector.runDetectChanges (http://localhost:8100/build/js/app.bundle.js:13516:14) 
    at AbstractChangeDetector.detectChanges (http://localhost:8100/build/js/app.bundle.js:13501:73) 
    at ChangeDetectorRef_.detectChanges (http://localhost:8100/build/js/app.bundle.js:14402:73) 
    at ViewController.willEnter (http://localhost:8100/build/js/app.bundle.js:46071:22) 
    at NavController._postRender (http://localhost:8100/build/js/app.bundle.js:44385:30) 
    at http://localhost:8100/build/js/app.bundle.js:44333:27 
ERROR CONTEXT: 
[object Object] 

回答

1

不要then函數中使用關鍵字this 。並且不要將JavaScript對象串聯起來。相反的:

stanservice.categoryDetail(this.params.get('id')) 
    .then((data) => { 
     this.category = JSON.stringify(data.res.rows[0]); 
     console.log(JSON.stringify(data.res.rows[0])); 
}) 
.catch((error) => { 
    console.log("Error message", error.err); 
}); 

嘗試:

var app = this; 

stanservice.categoryDetail(this.params.get('id')) 
    .then((data) => { 
     app.category = data.res.rows[0]; 
     console.log(data.res.rows[0]); 
}) 
.catch((error) => { 
    console.log("Error message", error.err); 
}); 
+0

同樣的錯誤上面'錯誤:未捕獲的(在承諾):異常:類型錯誤:無法在[ {{category.name讀取未定義的屬性 '名' }}' – Rexford

+0

如果你使用console.log(data.res.rows [0])而不是'console.log(JSON.stringify(data.res.rows [0]))'',你會得到什麼?你在控制檯中看到一個對象或字符串嗎?一個對象會讓你與它進行交互。一個字符串不會。 – dewd

+0

'Object {id:3,name:「ok」,note:「notes」,type:「expense」}' – Rexford