【问题标题】:Get value of Observable<SomeObject> in an object获取对象中 Observable<SomeObject> 的值
【发布时间】:2019-12-21 23:19:05
【问题描述】:

在 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>

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

【问题讨论】:

    标签: typescript rxjs google-cloud-firestore angular7 angularfire


    【解决方案1】:

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

    {{category.subCategories | async}}

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

    编辑:

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

    【讨论】:

    • 当我这样做时(在 ngfor 循环所有顶级类别中)没有显示任何内容,我确信顶级类别具有包含内容的“子类别”属性。
    • 我明白了。看起来在你的第二个 ngFor 中,你的意思是做 cat.subCategories | async 而不是 categories.subCategories |然后异步。这将确保显示每个类别的所有子类别。
    • 哇! ?当然,那些该死的角度范围!感谢您的帮助?
    • 没问题。很高兴为您提供帮助!
    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 2022-01-15
    • 2020-02-08
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多