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

时间:2018-09-05 03:32:34

标签: angular rxjs ngrx ngrx-entity

我将ng6与NGRX结合使用,以在视图中显示两个数据集。第一个数据集是完整的数据集。第二个数据集是第一个数据集的子集。

我需要在提供id的第二个数据集上使用ngFor循环,并在循环中使用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对应于数据集One中的名称,我想显示该名称而不是id

该视图是否是这样的

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

但是我没有成功编写一种可以从datasetOne$抓取一个实体的方法

2 个答案:

答案 0 :(得分:1)

由于您已经在使用选择器,因此建议您根据当前两个选择器创建一个新的选择器。

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

答案 1 :(得分:0)

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

Doc:http://reactivex.io/documentation/operators/zip.html

语法类似于:

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

Ex:

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>

相关问题