我如何获得 ngrx 商店的特定对象?
How i can get a specific object of an ngrx store?
现在我的商店是一个对象,里面有一个 users
对象数组:
{ "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">
但是我收到这个警告:
ERROR in src/app/pages/usuario/usuario.component.html:32:32 - error
TS2339: Property 'users' does not exist on type 'Observable'.
有一种方法可以只从我的商店中获取用户对象,例如:
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));
您需要扩展您的管道,select('userStates')
没有 return 数据,它 return 说明了如何在商店发生变化后获得 userStates
。
要映射数据,有 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">
现在我的商店是一个对象,里面有一个 users
对象数组:
{ "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">
但是我收到这个警告:
ERROR in src/app/pages/usuario/usuario.component.html:32:32 - error TS2339: Property 'users' does not exist on type 'Observable'.
有一种方法可以只从我的商店中获取用户对象,例如:
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));
您需要扩展您的管道,select('userStates')
没有 return 数据,它 return 说明了如何在商店发生变化后获得 userStates
。
要映射数据,有 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">