【问题标题】:Angular2 Is it possible to get deep nested json value without using ngFor?Angular2是否可以在不使用ngFor的情况下获得深层嵌套的json值?
【发布时间】:2017-04-07 22:45:33
【问题描述】:

我目前正在从服务器获取 json 对象,并且该对象也有许多嵌套的 json 对象。到目前为止,我一直在使用 *ngFor = "let a of data | pipe"(获取深度嵌套值的管道)和单插值 {{a.value['someValue']}} 来获得深度嵌套值json 对象用于其他情况,但这现在不符合我的目的,因为我不想循环我的 json。

有什么方法可以在不使用 ngFor 的情况下获取深度嵌套的 json 值?

我从服务器获取的 json 对象的一部分。

UserProfile: 
{name: 'Jess'
University: 'UC Berkley'
Major: 'Media Communication'
birthday: 1994}

categoryInfo: 
["inish work with quality"]

currentArea
:"CA"

introInfo {
experience: [
0: {Company: 'Atlas', workingYears: 1, **recLetter**:'She was on time always, 
never late. The quality of her work is very high-level.'}
1: {Company: 'Footstep', workingYears: 2, recLetter:'She was on time always, 
never late. The quality of her work is very high-level.'}
]
introduction: "Hello I'm Jess"
}

如果我使用上述方法,它只会循环 4 个我不想要的键(UserProfile、categoryInfo、currentArea 和 introInfo)。

如何在不使用 *ngFor 的情况下获得粗体 (recLetter) 的值?

在我的组件中,我正在这样做。

 userInfo: UserDetailInfo[]; 

  getUserDetail(): void {

    this.userDetail.getUserDetail()
    .subscribe
    (
        userInfo => this.userInfo = userInfo,
        error => this.errorMessage = error
        )
     }

我在 html 模板中尝试过,但没有成功,我不知道如何获取“recLetter”

{{userInfo.experience['0']}}

请帮忙!

提前谢谢你

【问题讨论】:

    标签: json angular get


    【解决方案1】:

    对于初学者,假设您得到的 experience 数组始终相同,只有 2 个元素。 您需要在 html 中做的唯一事情是:

    {{ userInfo.experience[0].recLetter }}
    

    如果您想遍历整个数组 exeperience 并显示 recLetter,您可以这样做:

    <div *ngFor="let item of userInfo.experience">
         {{item.recLetter}}
    </div>
    

    【讨论】:

      【解决方案2】:

      试试这个

      properties.pipe.ts

      import {Pipe} from '@angular/core';
      
      @Pipe({name: 'properties'})
      export class PropertiesPipe {
        transform(o: {}) {
          return Object.entries(o).map(([key, value]) => ({
            key,
            value
          })); 
        }
      }
      

      app.module.ts

      import {propertiesPipe} from './properties.pipe';
      
      @NgModule({
        declarations: [PropertiesPipe, /* whatever else was here */],
        // ... whatever else was here
      }) export class AppModule { }
      

      component.html

      <ul>
        <li *ngFor="property of userInfo | properties">
          <span *ngIf="!Array.isArray(property.value)">
            {{property.key}}: {{property.value}}
          </span>
          <span *ngIf="Array.isArray(property.value)">
            {{property.key}}: <span *ngFor="value of property.value">{{value}}, </span>
          </span>
        </li>
      </ul>
      

      【讨论】:

        猜你喜欢
        • 2017-08-15
        • 2017-09-09
        • 1970-01-01
        • 2016-03-31
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-31
        • 1970-01-01
        相关资源
        最近更新 更多