Selecting our data

We have learnt by now that to select data in NgRx, we need to inject the store service and call select on it, either with a string as an argument or with a function. Let's inject the store service and have a look at the state that comes back:

// app.component.ts  - a first draft

import { Component } from "@angular/core";
import { AppState } from "./app-state";
import { Store } from "@ngrx/store";


@Component({
selector: "app-root",
template: `
User list view
`
})
export class AppComponent {
title = "app";
users$;

constructor(private store: Store<AppState>) {
this.users$ = this.store
.select(state => state);

this.users$
.subscribe(data
=> console.log("users", data));
}
}

The preceding component won't display the users in a neat list just yet; we will explain why later. In the meantime, we will just focus on what is logged to the console:

What we see here is the state of our store, which contains a user's property at the highest level, it has entities, ids and selectedUserId as properties. This is to be expected so far. What does surprise us a little is the fact that the entities dictionary is an object and not a list. How do we output that in a list form using *ngFor?  Well, we can easily solve that with a map() operator, like so:

// app.component.ts adding more UI and selecting the correct slice of state

import { Component } from "@angular/core";
import { AppState } from "./app-state";
import { Store } from "@ngrx/store";
import { map } from "rxjs/operators";

@Component({
selector: "app-root",
template: `
<div style="border: solid 1px black; padding: 10px;"
*ngFor="let user of users$ | async">
{{ user.name }}
</div>
`
})
export class AppComponent {
title = "app";
users$;
constructor(private store: Store<AppState>) {
this.users$ = this.store
.select(state
=> state.users.entities)
.pipe(
map(this.toArray)
);

this.users$.subscribe(data => console.log("users", data));
}

toArray(obj) {
const keys = Object.keys(obj);
return keys.map(key => obj[key]);
}

}

OK, so now we drill down to state.users.entities to get to our users but we need to add the map() operation to turn our entities dictionary into a list. So, the console now shows us an empty array as the initial value of users$, which makes perfect sense. The UI is still empty, as we have an empty array and therefore nothing to show.  In the following section, we will cover how to add, remove, and update the state using the EntityAdapter

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.222.89