如何使用 html 从包含数组的 Observable 中获取单个值。我正在运行 Angular2 w/Typescript
typescript
private observable = Observable.of([1,2,3,4,5])
html
<p>{{observable[2]}}</p>
即获取可观察对象保存的索引 2 中的数组元素
最佳答案
根据之前的回答。你应该避免两件事(如果可能的话):
- 手动
.subscribe()
。请改用异步管道,以便它将为您管理订阅。 - 内部状态,例如
.subscribe(val => this.val = val)
。直接使用流并添加Subject
(行为、异步等),以便完整的逻辑将在流内关闭。
问题的解决方案是创建一个流,结合当前索引、数组的可观察值并在索引处发出元素。
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)
或者,如果您只想获得一次,那么就
public elementAtIndex2$ = this.observable$.map(arr => arr[2])
关于javascript - 获取特定索引处的可观察数组元素 [html],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537383/