Search code examples
angularngrx

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


Nowadays my store is an object that inside have an users array of object:

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

This is the way that i get this data from my store:

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

In my template i'm trying to make a *ngFor:

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

But i receive this warning:

ERROR in src/app/pages/usuario/usuario.component.html:32:32 - error TS2339: Property 'users' does not exist on type 'Observable'.

There's a way to get from my store only the user object, something like:

 this.users$ = store.pipe(select('userStates').users);

Solution

  • You need to extend your pipe, select('userStates') doesn't return data, it returns instructions how to get userStates once there's change in the store.

    to map data there's map operator: 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.
    );
    

    and now you can use it in the template without property access

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