【问题标题】:Get array element in observable at particular index [html]在特定索引处获取可观察的数组元素 [html]
【发布时间】:2017-04-21 08:14:00
【问题描述】:

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

打字稿

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

html

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

即获取可观察对象持有的索引 2 中的数组元素

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    根据之前的答案。你应该避免两件事(如果可能的话):

    1. 手动.subscribe()。请改用异步管道,以便它为您管理订阅。
    2. 内部状态如.subscribe(val =&gt; 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])
    

    【讨论】:

    【解决方案2】:

    您需要订阅 observable,然后通过索引访问值:

    @Component({
      template: `Value: {{ observableValue[2] }}`
    })
    export class SampleComponent implements OnInit {
    
      values = Observable.of([1, 2, 3, 4, 5]);
      observableValue: number[];
    
      ngOnInit(): void {
         this.values.subscribe(value => this.observableValue = value);
      }
    
    }
    

    【讨论】:

      【解决方案3】:

      我遇到了类似的问题。我可以订阅 observable 并获取值,但这不是最好的方法,因为您现在必须处理订阅和取消订阅、内存泄漏等等。使用可观察值的最佳方法是使用异步管道“|”)。 所以,这是我提出的解决方案

      你的组件.ts

      source: any = of([1, 2, 3, 4, 5]);
      

      你的组件.html

      <div *ngFor = " let s of source | async; let i = index">
      {{s}} {{source | async | slice :i:i+1}}
      </div>
      

      正如您所见,通过异步管道使用 slice 的一种深刻方法解决了这个问题。 如果要访问可观察数组的任何元素 例如第一个元素只是做:-

      {{source | async | slice :0:1}}
      

      希望对你有帮助!!

      https://angular.io/guide/pipes阅读更多关于角管的信息

      【讨论】:

        【解决方案4】:

        如果不订阅 Observable,您将无法获得价值。

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

        或者你可以直接在html中使用异步管道

        <p>{{observable | async}}</p>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-15
          • 2018-11-26
          • 2013-05-24
          • 2019-11-20
          • 1970-01-01
          • 1970-01-01
          • 2021-11-01
          相关资源
          最近更新 更多