Skip to content Skip to sidebar Skip to footer

Get Array Element In Observable At Particular Index [html]

How does one go about getting a single value from an Observable that contains an array using html. Im running Angular2 w/Typescript typescript private observable = Observable.of([1

Solution 1:

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

  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]
)

Then in your view:

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

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])

Solution 2:

You would need to subscribe to the observable, then access the value by index:

@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);
  }

}

Solution 3:

I was facing a similar issue. I could just subscribe to the observable and get the value, but it's not the nicest way as you have to now deal with subscriptions and unsubscriptions, memory leaks and what not. The best way to use observable values is by using the async pipe '|'). So, here is my proposed solution

yourComponent.ts

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

yourComponent.html

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

As you can see a profound way to use slice with async pipe, solves the issue. If you want to access any element of the observable array for example the first element just do:-

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

Hope it's helpfull!!

Read more about angular pipes at https://angular.io/guide/pipes


Solution 4:

Without Subscribing to an Observable you can not get value.

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

Or you can use async pipe direct in html

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

Post a Comment for "Get Array Element In Observable At Particular Index [html]"