使用 ID 在 ngFor 循环中显示单个 ngrx 实体

Display single ngrx entity within ngFor loop using Ids

我使用 ng6 和 NGRX 在视图中显示两个数据集。第一个数据集是完整的数据集。第二个数据集是第一个数据集的子集。

我需要在第二个数据集上使用 ngFor 循环,它提供 id,并在循环内使用 id 显示第一个数据集中的单个实体。

component.ts

export class ViewComponent implements OnInit {
  datasetOne$: Observable<data[]>;
  datasetTwo$: Observable<data[]>;

  constructor(private store: Store<fromStore.DatasetState>) {}

  ngOnInit() {
    this.store.dispatch(new fromStore.LoadDatasetOne());
    this.store.dispatch(new fromStore.LoadDatasetTwo());
    this.datasetOne$ = this.store.select(fromStore.getDatasetOne);
    this.datasetTwo$ = this.store.select(fromStore.getDatasetTwo);
  }

}

component.html

<ul>
    <li *ngFor="let data of (datasetOne$ | async)">{{ data.name }}</li>  
</ul>

Subset:

<ul>
    <li *ngFor="let subData of (datasetTwo$ | async)">{{ subData.id }}</li>  
</ul>

到目前为止,该视图正确显示了两个子集,名称和 ID(数字)

subData.id对应datasetOne中的一个名字,我想显示名字而不是id

视图是这样的吗:

<li *ngFor="let subData of (datasetTwo$ | async)">{{ getNameById(subData.id) }}</li>

但是我没有成功地写出一个可以从 datasetOne$

中抓取单个实体的方法

您基本上有两个流,并且您想要使用两个流的值创建一个新流。您需要使用 zip

文档:http://reactivex.io/documentation/operators/zip.html

语法类似于:

Observable.zip ( source 1, source 2, function )

例如:

const dataNames = Rx.Observable.of(['name1','name2','name3']);
const dataId = Rx.Observable.of([0,2,1]);

Rx.Observable.zip(
   dataId,
   dataNames,
   (arr1,arr2)=> arr1.map(id=> arr2[id])  // change this to your requirement
).subscribe(console.log);
<script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"></script>

由于您已经在使用选择器,我建议您基于当前的两个选择器创建一个新的选择器。

const combinedSelector = createSelect(datasetOne, datasetTwo,
  (one, two) => ...
)

如果这不可能,您也可以按照 NgRx: Parameterized selectors

中提到的以下方法
export const selectCustomer = createSelector(
  selectCustomers, 
  customers => (id: string) => customers[id]
);

// tip: it’s also possible to memoize the function if needed
export const selectCustomer = createSelector(
  selectCustomers, 
  customers => memoize((id: string) => customers[id])
);

// and in the HTML
{{ (customers | async)(id).name }}