【问题标题】:Display single ngrx entity within ngFor loop using Ids使用 Id 在 ngFor 循环中显示单个 ngrx 实体
【发布时间】:2018-09-05 03:32:34
【问题描述】:

我使用 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);
  }

}

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$抓取单个实体的方法

【问题讨论】:

    标签: angular rxjs ngrx ngrx-entity


    【解决方案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 }}
    

    【讨论】:

    • 组合选择器是首选方法。第一个参数是实体数组,第二个参数是ids 数组,然后映射到two 并返回entity[id]
    【解决方案2】:

    您基本上有两个流,并且您想使用两个流中的值创建一个新流。你需要使用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);
    &lt;script src="https://unpkg.com/@reactivex/rxjs@5.0.3/dist/global/Rx.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 2021-12-15
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多