可观察的数组,找到值的索引 [英] Observable of array, find index of value
本文介绍了可观察的数组,找到值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个 Angular 应用,它从一个服务中获取一系列商店,作为一个 Observable.
I'm writing an Angular app that gets a selection of stores from a service, as an Observable.
当用户单击地图上的标记时,我想获取位于 Observable 内的数组中商店的索引.
When the user clicks a marker on the map, I want to get the index of the store in the array that lives inside the 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?
}
推荐答案
用于从数组中过滤商店:
For filtering the stores from the array you do:
this.storesCollection.filter(store => store.geopoint === event.geopoint); // -1 if not found
为了将 Observable 转换为数组,使用 map:
And for transforming the Observable to an Array use map:
this.stores$.map((stores: Stores[]) => this.storesCollection = stores)
您不需要执行 subscribe() 因为 http 返回一个热门的 observable,无论是否有订阅者,它总是会触发
You don't need to do subscribe() because http returns a hot observable, always firing regardless of there being a subscriber or not
这篇关于可观察的数组,找到值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文