0

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

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

组件.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);
  }

}

组件.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(数字)

对应于 datasetOne 中的subData.id名称,我想显示名称而不是id

视图是这样的吗:

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

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

4

2 回答 2

1

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

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

如果这不可能,您还可以按照NgRx 中所述:参数化选择器

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 }}
于 2018-09-05T05:56:14.677 回答
0

您基本上有两个流,并且您想使用两者的值创建一个新流。你需要使用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>

于 2018-09-05T05:24:18.080 回答