Deleting users

The last piece of supporting CRUD is the ability to remove users from the list. This case is very similar to all the other cases:

  • We need to add support for it to app.component.ts
  • We need to update the reducer, and the reducer needs to call the appropriate adapter method

Let's start with the component and add support in the markup, as well as adding a remove() method  to the component class, like so:

// app.component.ts - adding remove capability

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 }}
<button (click)="remove(user.id)" >Remove</button>
<edit-user [user]="user" (save)="update($event)" ></edit-user>
</div>
<div>
<input [(ngModel)]="user" /> <button (click)="add()">Add</button>
</div>
`
})
export class AppComponent {
title = "app";
users$;
user;
id = 1;

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]);
}

add() {
const newUser = { id: this.id++, name: this.user };
this.store.dispatch({
type: "ADD_USER",
payload: newUser
});
}

remove(id) {
console.log("removing", id);
this.store.dispatch({ type: "REMOVE_USER", payload: { id } });
}


update(user) {
console.log("updating", user);
this.store.dispatch({ type: "UPDATE_USER", payload: user });
}
}

The remaining part is updating our reducer to say the following:

// excerpt from app.module.ts

function userReducer(state = initial, action: ActionPayload<User>): State {
switch (action.type) {
case "ADD_USER":
return userAdapter.addOne(action.payload, state);
case "REMOVE_USER":
return
userAdapter.removeOne(action.payload.id, state);
case "UPDATE_USER":
return userAdapter.updateOne(
{
id: action.payload.id,
changes: action.payload
},
state
);
default:
return state;
}
}
..................Content has been hidden....................

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