遍历在对象数组参数

问题描述 投票:0回答:2

我有一个这样的对象数组:

[{
  position: "Software Developer",
  company: "Big company",
  details: [
    "task1","task2,"task3"
  ]
},
{
  position: "Software Developer",
  company: "Another Big company",
  details: [
    "task1a","task2a,"task3a"
  ]
}]

我读的是从我的组件的服务:

ngOnInit() {
    this.data.getExperience().subscribe(
      data => this.experience$ = data
    )
  }

在我的HTML我遍历这个数组,但在循环中,我想遍历细节也是如此。我已经尝试了一些方法,包括下面的一个,但我真的不明白怎么在这里工作。如何正确对待呢?

<li *ngFor='let experience of experience$'>
    <!--<a routerLink='/details/{{ user.id }}'>{{ user.name }}</a>-->
    <ul>
      <li class="position">{{ experience.position }}</li>
      <!--<li><a href='http://{{ user.website }}'>{{ user.website }}</a></li>-->
      <li class="company">{{ experience.company}}<span class="dates">  {{ experience.dates}}</span></li>
      <ul class="details" *ngFor='let d of experience.details$'></ul>
        <li>{{ d }}</li>
    </ul>
  </li>
angular observable ngfor
2个回答
2
投票

如果属性包含可观察到的值$一般是在属性名后添加后缀。这是因为作为在Angular Guide here规定的命名约定:

由于角度的应用大多是写在打字稿,您通常会知道,当一个变量是可观察到的。虽然角框架不强制对观测的命名约定,你经常会看到一个尾随“$”符号命名的观测。

通过代码扫描,寻找可观测值时,这可能是有用的。另外,如果你想存储从观察到的最近的值的属性,它可以方便简单地使用相同的名称使用或不使用“$”。

既然你已经subscribing的可观测和experience$不会是可观察到的,而是这将是一个数组,你应该考虑不同的命名属性。

试试这个没有$。

有关详细信息,li也没有在ul。因此,通过执行以下修正:

<li *ngFor='let experience of experiences'>
  <!--<a routerLink='/details/{{ user.id }}'>{{ user.name }}</a>-->
  <ul>
    <li class="position">{{ experience.position }}</li>
    <!--<li><a href='http://{{ user.website }}'>{{ user.website }}</a></li>-->
    <li class="company">{{ experience.company}}<span class="dates">  {{ experience.dates}}</span></li>
    <ul class="details" *ngFor='let d of experience.details'>
      <li>{{ d }}</li>
    </ul>

  </ul>
</li>

另外,还要在你的组件类这种变化:

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  experiences: any[];

  constructor(private data: DataService) {}

  ngOnInit() {
    this.data.getExperience().subscribe(
      data => this.experiences = data
    )
  }
}

以下是为您的参考一Working Sample StackBlitz


0
投票

你有一个错字只是删除$details。另外,不要使用$为不可观察的变量,因为此命名约定通常用来识别观测。

<li *ngFor='let experience of experience$'>
    <!--<a routerLink='/details/{{ user.id }}'>{{ user.name }}</a>-->
    <ul>
      <li class="position">{{ experience.position }}</li>
      <!--<li><a href='http://{{ user.website }}'>{{ user.website }}</a></li>-->
      <li class="company">{{ experience.company}}<span class="dates">  {{ experience.dates}}</span></li>
      <ul class="details" *ngFor='let d of experience.details'></ul>
        <li>{{ d }}</li>
    </ul>
  </li>
© www.soinside.com 2019 - 2024. All rights reserved.