Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular 7中打印嵌套对象?_Angular_Typescript_Object_Angular7 - Fatal编程技术网

如何在Angular 7中打印嵌套对象?

如何在Angular 7中打印嵌套对象?,angular,typescript,object,angular7,Angular,Typescript,Object,Angular7,我有一个嵌套对象数据- "data": { "serial": "123", "def": { "id": "456", "data": { "firstname": "abc",

我有一个嵌套对象数据-

    "data": {
        "serial": "123",
        "def": {
            "id": "456",
            "data": {
                "firstname": "abc",
                },
            "method": "post",
        },
        "ghi": {
            "id": "456",
            "data": {
                "amount": "3500.0",
                    },
            "method": "post",
            },
        "jkl": "done"

    }
我将其存储在项目中对象中。然后, 我尝试在HTML组件中使用-

<div *ngFor="let item of items | keyvalue">
        <div>
            <div>{{item.key}}:{{item.value}}</div>
        </div>
</div>
如何打印此嵌套对象?
提前谢谢

您使用的是ngFor,它主要用于阵列,而您没有。我建议您修改您的数据,或者如果它确实需要保留为对象,则只需执行以下操作:
data.def.id
,例如,不需要ngFor

获取名字的另一个示例:

{{data?.def?.data?.firstname}}

我认为对于一个对象,您可能无法像对数组那样使用*ngFor。我的解决方案是在ts文件中使用如下递归函数:

  expand(data: any): string[] {
    let stringArr = [];
    for (const prop in data) {
      data[prop] instanceof Object
        ? (stringArr = stringArr.concat([`${prop}: `]).concat(this.expand(data[prop])))
        : stringArr.push(`${prop}: ${data[prop]}`);
    }
    return stringArr;
  }
然后在HTML文件中:

<div *ngFor = " let item of expand(data)">
    {{ item }}
</div>

在我看来,仅仅说“重构你的数据”并不是一个答案。数据可能来自Atul无法控制的系统。当然有很多方法可以实现@Atul想要的。这些是简单还是困难是另一个问题。@AndrewJuniorHoward事实上,数据是对API调用的响应。因此,它不能修改。@Atul好的,但你完全错过了我答案的第二部分。我已经说过,只需沿着节点往下走,就可以导航对象。公认的答案虽然有效,但言过其实。没有必要使用ngFor。@JorisMolnar我实际上给出了两个答案。双方都满意outcome@AndrewJuniorHoward是的,它不需要使用*ngFor就可以工作。但是如果数据很大,手动显示它会变得很忙。如果我想访问某个特定的应用程序,您的解决方案运行良好。感谢您的帮助:)
<div *ngFor = " let item of expand(data)">
    {{ item }}
</div>
serial: 123
def:
id: 456
data:
firstname: abc
method: post
ghi:
id: 456
data:
amount: 3500.0
method: post
jkl: done