获取可观察到的特定索引处的数组元素[html] [英] Get array element in observable at particular index [html]

查看:64
本文介绍了获取可观察到的特定索引处的数组元素[html]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用包含html的数组从Observable获取单个值?我正在运行带有Typescript的Angular2

How does one go about getting a single value from an Observable that contains an array using html. Im running Angular2 w/Typescript

打字稿

private observable = Observable.of([1,2,3,4,5])

html

<p>{{observable[2]}}</p>

即获取可观察到的索引2中的数组元素

i.e get the array element in index 2 held by the observable

推荐答案

根据先前的答案.您应该避免两件事(如果可能):

According to previous answers. You should avoid 2 things (if possible):

  1. 手册 .subscribe().请改用异步管道,以便它将为您管理订阅.
  2. 内部状态,如 .subscribe(val => this.val = val).直接使用流,并添加 Subject (行为,异步等),以便在流内部关闭完整的逻辑.
  1. Manual .subscribe(). Use async pipe instead so it will manage subscription for you.
  2. Internal state like .subscribe(val => this.val = val). Use streams directly and add Subject (Behavior, Async, whatever) instead so complete logic will be closed inside streams.

您的问题的解决方案是创建一个具有当前索引的流,该流结合了当前索引,可观察到的数组并在索引处发出元素.

Solution for your problem is to create a stream with combines current index, observable of array and emits element at index.

public index$ = new BehaviorSubject(2)
public observable$ = Observable.of([1,2,3,4,5])

public elementAtIndex$ = Observable.combineLatest(
  this.index$,
  this.observable$,
  (index, arr) => arr[index]
)

然后在您看来:

<p>{{ elementAtIndex$ | async }}</p>

因此,每次索引/数组更改时,它都会发出适当的值.如果您要选择其他索引,例如5,然后只需执行 this.index $ .next(5)

So every time index/array changes it emits appropriate value. If you want to select another index, e.g. 5, then just execute this.index$.next(5)

或者,如果您只想获得一次,那么

Or if you only want to get it once then just

public elementAtIndex2$ = this.observable$.map(arr => arr[2])

这篇关于获取可观察到的特定索引处的数组元素[html]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆