在带有 *ngFor 的 Angular 2 模板中使用可观察对象

Using observables in an Angular 2 template with *ngFor

如果我使用 *ngFor 构建访问链,我将无法访问异步管道提供的对象的 属性。

在下面的示例中,假设测试行中的 Parking 和下面的两行 ?.[filter.propName] 表示同一对象上的同一键。测试行将评估为真,但选中的 属性 不会。为什么?在使用 *ngFor 将这些标记出来时如何访问 属性?

例如,如果 {{(compModel | async)?.Parking?.Garage}} === true 我也希望 {{(compModel | async)?.[filter.propName].instance}} === true,但事实并非如此。

以下语法无效。我用它来演示预期的功能。

<div *ngFor="let filter of filters | async">
...
<fieldset class="filter-category-title">
      <legend>{{filter.name}}</legend>
        <label *ngFor="let instance of filter.options">
          test: {{(compModel | async)?.Parking.instance}}
          <input type="checkbox"
                 checked={{(compModel | async)?.[filter.propName].instance}}
                 (click)="amenityEmit({category: filter.propName, filter: instance, resetCategory: false})">
                 {{instance}}
        </label>
    </fieldset>
</div>

我从服务器获取的过滤数据格式如下。我用它来构建一个比较模型,也在下面,这就是我管理搜索结果页面状态的方式。 ([key: string] 始终是过滤器中的 propName)。

export interface Filter {
  base: boolean,
  filter: string,
  propName: string,
  unionType: string,
  inputType: string,
  options: {
    options: string[],
    sectionTitle: string
  }[] | string[]
}

compModel 接口:

export interface CompModel {
  [key: string]: {
    touched: boolean
    unionType: string,
    options: {
      options: string[],
      sectionTitle: string
    }[] | string[],
    updateSelf(x: CompModel, y: Action): void
  }
}

safe-navigation 运算符 ?. 不适用于 []。没有 ?[] 运算符,也没有 ?.[].[] 运算符,因此这行不通。

你可以试试

{{(compModel | async) && (compModel | async)[filter.propName].instance}} === true

否则您需要将一些代码移动到组件 class

例如

this.compModel = someService.getSomeObservable()
.filter(val => !!val)

确保没有 null