簡體   English   中英

我怎樣才能獲得ngrx商店的特定object?

[英]How i can get a specific object of an ngrx store?

現在我的商店是一個 object,里面有一個users數組 object:

{ "users": [ { "id": 1, "nome": "Renato Maionese", "cidade": "Franca" } ] }

這是我從商店獲取這些數據的方式:

constructor(
  private store: Store<{ count: number; userStates: Usuario }>
) {
  this.users$ = store.pipe(select('userStates'));
}

在我的模板中,我試圖制作一個 *ngFor:

<tr *ngFor="let usuario of users$.users | async">

但我收到這個警告:

src/app/pages/usuario/usuario.component.html:32:32 中的錯誤 - 錯誤 TS2339:“可觀察”類型上不存在屬性“用戶”。

有一種方法可以從我的商店中僅獲取用戶 object,例如:

 this.users$ = store.pipe(select('userStates').users);
<tr *ngFor="let usuario of (users$ | async)?.users">

如下所述,您可以使用選擇器。 另一種選擇是

this.users$ = store.pipe(
             select('userStates'),
             map(userstates => userstates.users));

您需要擴展您的 pipe, select('userStates')不會返回數據,它會返回說明如何在商店發生更改后獲取userStates

到 map 數據有map運營商: https://www.learnrxjs.io/learn-rxjs/operators/transformation/map

import {map} from 'rxjs/operators';

this.users$ = store.pipe(
  select('userStates'),
  map(state => state.users), // now this.users$ returns users instead of state.
);

現在您可以在沒有屬性訪問的模板中使用它

<tr *ngFor="let user of users$ | async">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM