Home > Software design >  how do I extract a single value from an observable after using ngrx in Angular 14
how do I extract a single value from an observable after using ngrx in Angular 14

Time:01-27

I'm still learning ngrx, but in my home component I have:

export class HomeComponent implements OnInit{
  constructor(private store: Store) { }

  photos$ = this.store.pipe(select(selectPhotos));

  ngOnInit(): void {
    this.store.dispatch(invokePhotosAPI());
  }
}

then On the page if I do something like:

<div *ngFor="let photo of photos$ | async">
    Photo Title {{photo.title}}
</div>

all works and I see all titles.

If I want show just 1 title for example I thought I could do:

<div>
   Photo Title {{photos$[2].title}}
</div>

however, when I try to do this, I receive the following error:

Element implicitly has an 'any' type because expressions of type '2' can't be used to index type 'Observable<Photo[]>'. Property '2' does not exist on type 'Observable<Photo[]>'.

can anybody show me how I should be able to extract a single value?

CodePudding user response:

If you want to hard code an index you could just use

{{(photos$ | async)[2].title}}

Or unwrap the whole array to a view variable

<ng-container *ngIf="photos$ | async as photos">
  {{photos[2].title}}
</ng-container>

Or use a behavior subject for the selected index and a combine latest

current$ = new BehaviorSubject(2);       

photos$ = this.store.pipe(select(selectPhotos));

selectedPhoto$ = combineLatest([this.current$, this.photos$]).pipe(
  map(([current, photos]) => photos[current])
);

selectPhoto(index) {
  this.current$.next(index);
}

and in the template

<div *ngIf="currentPhoto$ | async as currentPhoto">
   Photo Title {{currentPhoto.title}}
</div>

If you want to do it the NgRx way, really don't know why you would use that rubbish but anyway you would have the selected index in your state, dispatch an action to update the state and have a selector that selects the current photo.

  • Related