【问题标题】:rxjs "find" with observable of hashmap of objectsrxjs“查找”具有可观察到的对象哈希图
【发布时间】:2021-07-01 15:27:33
【问题描述】:

假设我有一个 hiObject 类,其中有变量 id: number 和一个 value: number 里面。 \

然后我有hiObjects$: Observable<HashMap<hiObject>> = ...在另一个班级。

我希望在id = 2 的可观察到的哈希图中找到hiObject,并将它们的value 分配给digit$: Observable<number>

目前我正在使用this.digit$ = hiObjects$.pipe(map(hiObjects) => for(const index in hiObjects)...),基本上循环遍历整个hashmap并寻找id何时等于2。

但我认为应该有另一个使用 rxjs findmap 的替代方案,想知道是否有人可以提供帮助。谢谢!

编辑:认为hashmap不允许find,所以这个问题现在没用了..

TS:

export interface hiObject {
  id?: number;
  value?: number;
}

export class smth implements OnInit{
  public digit$: Observable<number>;
  public hiObjects$: Observable<HashMap<hiObject>> = ...
  ngOnInit() {
    this.digit$ = this.hiObjects$.pipe(
      map((collections) => {
        for (const index in collections) ...})
    );
  }
}

【问题讨论】:

  • 对我来说不是很清楚。请将您的具体实现上传到 stackblitz,以便我们更容易了解您的需求。
  • @monogate 我已经插入了一些代码块,如果有帮助的话

标签: javascript angular typescript rxjs hashmap


【解决方案1】:

你很接近,使用.find,然后使用.value(如果确实找到了)

this.digit$ = hiObjects$.pipe(
    // this finds the hiObject that has an id of 2, and then returns the value
    map(hiObjects => hiObjects.find(id => id === 2)?.value)
);

【讨论】:

  • 谢谢!现在它给我Type 'hiObject' has no call signatures,或者hiObjects.find is not a function`当我有map(hiObjects : any) =&gt;...
  • 你有 hiObject 长什么样的例子吗?
  • 这是一个界面,看起来类似于我在问题代码块中的界面
猜你喜欢
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2022-11-25
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多