[英]how do I extract a single value from an observable after using ngrx in Angular 14
我仍在學習 ngrx,但在我的家庭組件中我有:
export class HomeComponent implements OnInit{
constructor(private store: Store) { }
photos$ = this.store.pipe(select(selectPhotos));
ngOnInit(): void {
this.store.dispatch(invokePhotosAPI());
}
}
然后在頁面上,如果我做類似的事情:
<div *ngFor="let photo of photos$ | async">
Photo Title {{photo.title}}
</div>
所有作品,我看到所有標題。
例如,如果我只想顯示 1 個標題,我想我可以這樣做:
<div>
Photo Title {{photos$[2].title}}
</div>
但是,當我嘗試這樣做時,我收到以下錯誤:
元素隱式具有“任何”類型,因為類型“2”的表達式不能用於索引類型“Observable<Photo[]>”。 類型“Observable<Photo[]>”上不存在屬性“2”。
誰能告訴我如何提取單個值?
如果你想硬編碼一個索引,你可以使用
{{(photos$ | async)[2].title}}
或者將整個數組解包到一個視圖變量
<ng-container *ngIf="photos$ | async as photos">
{{photos[2].title}}
</ng-container>
或者對所選索引使用行為主題並結合最新
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);
}
並在模板中
<div *ngIf="currentPhoto$ | async as currentPhoto">
Photo Title {{currentPhoto.title}}
</div>
如果你想用 NgRx 的方式來做,真的不知道你為什么要使用那個垃圾,但無論如何你會在你的 state 中有選定的索引,發送一個動作來更新 state 並有一個選擇器來選擇當前照片。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.