简体   繁体   English

如何在角度模板中显示JSON Web响应?

[英]How to display json web response in angular template?

I am trying to display some JSON data that comes as HTTP web response, but it's not working. 我正在尝试显示HTTP Web响应附带的一些JSON数据,但是它不起作用。

Below is my http request: 以下是我的http请求:

nodes: any;

ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/assets/TEST.json').subscribe(data => {
        // Read the result field from the JSON response.
        this.nodes=data;
    });
}

And this is the template: 这是模板:

<div *ngFor="let node of nodes">
    <p>{{node.description}}</p>
</div>

This is my json data: 这是我的json数据:

{
    "id": 1,
    "name": "root1",
    "link": "/login"
}

This the error I get in console: 这是我在控制台中得到的错误:

Cannot find a differ supporting object '[object Object]' of type 'root1' where root1 is a component different from the one where the request is made. 找不到类型为“ root1”的其他支持对象“ [object Object]”,其中root1是与发出请求的组件不同的组件。

First of all, your JSON is an object, not an array. 首先,您的JSON是一个对象,而不是数组。 Therefore, you can't use ngFor . 因此,您不能使用ngFor As your object doesn't have a description property (but a name ), you may display the name (make sure that nodes has been set) using this template: 由于您的对象没有description属性(而是name ),因此可以使用以下模板显示名称(确保已设置节点):

<p *ngIf="nodes">{{ nodes.name }}</p>

After our investigations in comments the solution : 经过我们的评论调查后,解决方案:

  • *ngFor shouldn't be used there since his JSON is an object not an array *ngFor不应在此处使用,因为他的JSON是对象而不是数组

so the solution is simply : 所以解决方案很简单:

<p> id : {{nodes.id}}</p>
<p> name : {{nodes.name}}</p>
<p> link : {{nodes.link}}</p>

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

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