javascript - 在模板 Angular 2中显示JSON对象

标签 javascript json angular

我有这个:

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);
});

关于javascript - 在模板 Angular 2中显示JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230359/

相关文章:

javascript - React 的大列表性能

jquery - 在html和jquery中获取表的列值的总数

json - postman 正在将我的正文从 application/json 更改为 string

angular - Firestore : Joins vs Firestore pricing

c# - MasterPage 上的 Javascript 问题

javascript - 我可以在 webpack 开发服务器上使用相对路径吗? react js

javascript - 如何在控制台页面查看URI的内容?

css - 如何从 webpack angular2 应用程序中的 node_modules 导入 CSS

angular - 在 Angular 8 中动态加载 json

javascript - React Router 和历史