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