【问题标题】:Filtering from an observable based on another基于另一个可观察对象过滤
【发布时间】:2018-05-28 23:02:03
【问题描述】:

我正在尝试通过根据其他可观察对象发出的事件过滤可观察对象来映射它们。所以这是我的挑战:

如何将事件的属性提供给过滤器?

这是我想要获取的实体的示例。目前它正在工作,因为我已经对关系 ID 进行了硬编码。我想从 cmets 中提到的 observables 中读取这些 ID。

export class AppComponent implements OnInit {
  currentInspection$;
  currentAircraft$;
  currentConfiguration$;

  ngOnInit() {
    const aircraft$ = Observable.of([
      { id: 1, callsign: 'D-AISY', configurationId: 100 },
      { id: 2, callsign: 'D-OOBE', configurationId: 200 },
      { id: 3, callsign: 'D-OOOO', configurationId: 100 }
    ]);
    const inspections$ = Observable.of([
      { id: 10, aircraftId: 3 },
      { id: 20, aircraftId: 2 }
    ]);
    const configurations$ = Observable.of([
      { id: 100, name: 'Default CRJ900 configuration' },
      { id: 200, name: 'Default B737 configuration' }
    ]);

    this.currentInspection$ = inspections$.pipe(
      map(inspections => inspections.find(inspection => inspection.id === 20))
    );

    // How do I get id property of this.currentInspection$ instead of 1 here?
    this.currentAircraft$ = aircraft$.pipe(
      map(aircraft => aircraft.filter(a => a.id === 1)) // I want the "1" to not be hardcoded
    );

    // How do I get configurationId property of this.currentAircraft$ instead of 100 here?
    this.currentConfiguration$ = configurations$.pipe(
      map(configurations => configurations.filter(c => c.id === 100)) // I want the 100 to not be hardcoded
    );
  }
}

这是一个活生生的例子: https://stackblitz.com/edit/angular-streamception?file=src%2Fapp%2Fapp.component.ts

我曾尝试使用 mergeMap 将第一个 observable 与后者合并并从内部进行过滤,但感觉就像是在与反应式方式背道而驰。

如果我从错误的角度解决问题,请务必指出正确的方向。

【问题讨论】:

  • 你能否提供更多关于你想要产生什么行为的细节?是否应该按照值流过滤项目?
  • 我想根据 currentInspection$ 的 configurationId 属性的 ID 过滤飞机 $ 以获取 currentAircraft$。并且还根据 currentAircraft$ 的 configurationId 属性的 id 从 $configurations 中过滤掉一个 currentConfiguration$。目前 1 和 100 是硬编码的。
  • 我知道,但它与纯数组有什么不同?您将如何确定要使用的检查 ID。当你有 id 时,你可以根据当时其他 observables 中发出的值过滤它,还是?
  • 我完全有可能在没有必要的地方强制使用可观察对象。您是否建议只订阅流并将实例变量设置为事件的值?
  • 这取决于你想要达到的目标。如果您希望过滤器是动态的并通过可观察流触发,那么这是一个可能的用例。否则只是通过订阅和过滤来聚合数据?

标签: angular stream rxjs filtering observable


【解决方案1】:

我不确定您想要的假定行为是什么,但我根据对您问题的理解整理了一些内容,希望它可以帮助您了解您需要朝哪个方向发展。

查看stackblitz

【讨论】:

    猜你喜欢
    • 2020-08-05
    • 2023-04-08
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多