[英]Display JSON object in template angular 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 CategorydetailPage@16: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]
不要在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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.