1

在 Angular 中,我定义了一个类别的接口。因为类别具有嵌套结构(通过定义父级),所以我在 category.ts 中定义了以下接口:

现在,如何获取模板中 subCategories 参数的值?

界面

import { Observable } from 'rxjs';

export interface Category{
    name: string,
    displayName: string,
    displayIndex: number;
    subCategories?: Observable<Category[]>;
    parent?: string;
}

组件

...imports...

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {

  categories: Category[];

  constructor(private categoriesService: CategoriesService) { }

  ngOnInit() {

    this.categoriesService.all().subscribe((cats) => {
      this.categories = cats;
      console.log(cats[0].subCategories); // outputs: Observable {_isScalar: false, source: Observable, operator: MapOperator} => If I subscribe to it and console that, it outputs the desired values.
    });
  }

}

模板


<div class="row">
    <div class="col-xs-12" *ngFor="let cat of categories; let i = index">

        <div class="row">
            <div class="col-xs-12">
                <p><a [routerLink]="['categories', cat?.name]">{{ cat?.display_name }}</a></p>
            </div>
        </div>

        <div class="row">
            <div class="col-xs-12" *ngFor="let sub of categories.subCategories | async; let j = index">
                {{ sub.name }}
            </div>
        </div>
    </div>
</div>

它只显示查询到的顶级类别。

4

1 回答 1

1

在模板中,使用async管道 aftercategory.subCategories确保subCategories使用从发出的最新值:

{{category.subCategories | async}}

文档:https ://angular.io/api/common/AsyncPipe

编辑:

看起来在您的第二个 ngFor 中,您的意思是cat.subCategories | async代替categories.subCategories | async. 这将确保显示每个类别的所有子类别。

于 2019-08-15T14:16:59.507 回答