简体   繁体   English

Angular2 无法显示 json 响应

[英]Angular2 unable to display json response

In a angular 2 template, I am unable to display data from json response:在 angular 2 模板中,我无法显示来自 json 响应的数据:

{
  "success": true,
  "data": {
    "id": 5,
    "user_id": 1,
    "category_id": 1,
    "title": "ghfjhgf",
    "body": "jhgfjhgf",
    "created": "2017-01-19T18:22:02+00:00",
    "modified": "2017-01-19T18:22:02+00:00",
    "file": null,
    "column_9": null,
    "category": {
      "id": 1,
      "name": "Running",
      "body": "Regroupe toutes les traces relative à la course à pied."
    },
    "user": {
      "id": 1,
      "email": "user@local.ch",
      "username": "user",
      "role": "user",
      "active": true,
      "created": "2017-01-15T16:21:44+00:00",
      "modified": "2017-01-15T16:21:44+00:00"
    }
  }
}

When I try with track.success there is no problem, it displays true, but when I try to display the id of data with any of the following:当我尝试使用track.success时没有问题,它显示为 true,但是当我尝试使用以下任何一项显示数据的 id 时:

track.data.id
track['data'].id
track['data']['id']

I have an undefined property.我有一个未定义的属性。 I need help please.我需要帮助。 Thanks in advance.提前致谢。

This is the output of {{ track |这是 {{ track | 的输出json }} json }}

{
  "success": true,
  "data": {
    "id": 6,
    "user_id": 1,
    "category_id": 1,
    "title": "dsfasd",
    "body": "afdasf",
    "created": "2017-01-19T18:27:26+00:00",
    "modified": "2017-01-19T18:27:26+00:00",
    "file": null,
    "column_9": null,
    "category": {
      "id": 1,
      "name": "Running",
      "body": "Regroupe toutes les traces relative à la course à pied."
    },
    "user": {
      "id": 1,
      "email": "user@local.ch",
      "username": "user",
      "role": "user",
      "active": true,
      "created": "2017-01-15T16:21:44+00:00",
      "modified": "2017-01-15T16:21:44+00:00"
    }
  }

This is my service:这是我的服务:

view(id):Observable<any> {
        return this.http.get('http://cake/api/tracks/' + id + '.json')
            .map(response => response.json());
    }

My component:我的组件:

ngOnInit() {

        this.sub = this.route.params.subscribe((params: Params) => {
            this.id = +params['id'];
        })
        this.trackService.view(this.id).subscribe(track => this.track = track);
    }

You should use Safe Navigation(Elvis) operator when you wanted to display internal property of Object当您想显示对象的内部属性时,您应该使用 Safe Navigation(Elvis) 运算符

track['data']?.id
track?.data?.id

Or use json pipe to display all data in json format.或者使用json管道以json格式显示所有数据。

track?.data | json
track | json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM