首页 文章

Angular2是否可以在不使用ngFor的情况下获得深层嵌套的json值?

提问于
浏览
0

我目前从服务器获取json对象,该对象也有许多嵌套的json对象 . 到目前为止,我一直在使用* ngFor =“让一个数据|管道”(管道得到深层嵌套值)和单个插值{{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']}}

请帮忙!

先感谢您

2 回答

  • 0

    对于初学者,让我们假设你得到 experience 数组总是相同,有2个元素 . 你需要在html中做的唯一事情是:

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

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

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

    试试这个

    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>
    

相关问题