简体   繁体   English

更新 ngOnChanges 中的 ngrx 选择器

[英]Update ngrx selector inside ngOnChanges

I have a parent component (B) that is getting data from it's parent input (A) (C) have is (B) child component.我有一个父组件(B)从它的父输入(A)获取数据(C)(B)子组件。

Inside (B) I'm having a selector that gets data from the store.(B)内,我有一个从商店获取数据的选择器。

export class BComponent implements OnChanges {
    @Input() branchId;

  ngOnChanges() {
    this.selectedDataByBranch$ = this.store.pipe(
      select(selectBranchDirections, { branchId: this.branchId, dir: this.selectedDirection })
    );
    this.selectedDataByBranch$.subscribe(selectedDataByBranch => {
      this.trainsDatasets = this.getDatasets(selectedDataByBranch);
      this.lineChart.data.datasets = this.trainsDatasets ? this.trainsDatasets : [];
      this.lineChart.update();
    });
  directionChanged(event) {
    this.selectedDirection = event;
    this.selectedDataByBranch$ = this.store.pipe(
    select(selectBranchDirections, { branchId: this.branchId, dir: this.selectedDirection })
   );
  }
}

directionChanged is the Output event that I get from (C) directionChanged是我从(C)获得的输出事件

The issue this that selectedDataByBranch subscription is not getting the new data update triggered inside selectedDataByBranch$ selectedDataByBranch订阅没有在selectedDataByBranch$中触发新数据更新的问题

I have also tried this way我也试过这种方式

directionChanged(event) {
   this.selectedDirection = event;

  select(selectBranchDirections, { branchId: this.branchId, dir: this.selectedDirection });
}

What i could suggest is.我可以建议的是。 Turn your parameters into a Subject then merge with the store selection, in your directionChanged(event) method provide value to subject.将您的参数转换为Subject ,然后与商店选择合并,在您的directionChanged(event)方法中为主题提供价值。

So your final code will be something like this:所以你的最终代码将是这样的:

export class BComponent implements OnChanges {
    @Input() branchId;
    criterias$= new Subject<{branchId:number,dir:number}>;
    ngOnChanges() {
      this.selectedDataByBranch$ = this.criterias$.pipe(mergeMap(criteria=> this.store.pipe(
      select(selectBranchDirections, { branchId: criteria.branchId, dir: this.searchDirection})
    )));    

    this.selectedDataByBranch$.subscribe(selectedDataByBranch => {
      this.trainsDatasets = this.getDatasets(selectedDataByBranch);
      this.lineChart.data.datasets = this.trainsDatasets ? this.trainsDatasets : [];
      this.lineChart.update();
    });
    this.criterias$.next({branchId:this.branchId,dir:this.sortDirection}); // init first call
   }    
  directionChanged(event) {
    this.selectedDirection = event;
    this.criterias$.next({ branchId: criteria.branchId, dir: this.searchDirection}});
   );
  }
}

This stackblitz tries to materialize what i say.这个stackblitz试图实现我所说的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM