【问题标题】:Observable of array, find index of value可观察的数组,找到值的索引
【发布时间】:2018-04-30 16:53:48
【问题描述】:

我正在编写一个 Angular 应用程序,它从服务中获取商店的选择,作为 Observable。

当用户单击地图上的标记时,我想获取存储在 Observable 内的数组中的索引。

stores: Observable<Store[]>;

ngOnInit() {
    this.stores = http.get<Store[]>('URL');
}

onMarkerClick(event) {
   const geopoint = event.geopoint;
   //How can I get the index where store.geopoint === event.geopoint?
}

【问题讨论】:

  • 如果这是一个不好的问题,请告诉我原因,而不仅仅是投反对票。

标签: angular rxjs rxjs5


【解决方案1】:

为了从你做的数组中过滤商店:

this.storesCollection.filter(store => store.geopoint === event.geopoint); // -1 if not found

对于将 Observable 转换为 Array 使用 map:

this.stores$.map((stores: Stores[]) => this.storesCollection = stores)

你不需要做 subscribe() 因为 http 返回一个 hot observable,不管有没有订阅者都会触发

【讨论】:

  • @Mark van Straten 是的,我添加了关于映射到值的部分。下次欢迎您对不完整的答案发表评论而不要投反对票
【解决方案2】:

如果您想从后端懒惰地获取store[],则必须在第一次订阅this.stores 时获取这些信息。所有其他订阅可能使用从您的http.get 返回的相同值。为了实现这一点,我们可以使用.shareReplay() 让所有订阅者多播到同一个源并让它重播之前的值,而不是重新调用http.get

function getStores() {
  //return http.get<Store[]>(URL) 
  return Rx.Observable.from(['asdf', 'foo', 'bar']).delay(500);
}

const stores = getStores()
  .do(undefined, undefined, _ => console.log('retrieved values from http backend'))
  .shareReplay();
const $buttonClicks = Rx.Observable.fromEvent(document.getElementById('button'), 'click');

$buttonClicks
  .do(_ => console.log('CLICKED'))
  .switchMap(_ => stores
               .map((val, idx) => [val, idx])
               .filter(tuple => tuple[0] === 'foo')
               .map(tuple => tuple[1])
            )
  .subscribe(
    idx => console.log('got index of `foo`: ' + idx)
  );

switchMap 有点难看(map/filter/map),因为这个示例代码没有使用数组,而是使用单个发射。 .toArray() 可以解决这个问题。取决于您希望如何继续使用索引(或值)

【讨论】:

  • 谢谢,这太完美了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 2013-02-03
  • 2019-09-09
  • 2018-03-31
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多