NgRx Store
dispatch()actions- An
Observableof state - An
Observerof actions
Dispatching Actions
export class AddUserComponent {
constructor(private store: Store<AppState>) { }
onSubmit(user: User) {
this.store.dispatch(new AddUserAction(user));
}
}- Inject
Store - Invoke
dispatch()method - New up the
AddUserActionclass specifying theuser - No HTTP service
- No state changes
Observing State
export class UserListComponent implements OnInit {
users: Observable<Array<User>>;
constructor(private store: Store<AppState>) { }
ngOnInit() {
this.users = this.store.pipe(select(allUsers));
}
}usersis anObservablethat receives notifications- The notification type is an array of
Userobjects - Inject
Store - Invoke the
pipe()method on thestore - Use the
select()operator specifying theallUsersselector
What's a selector?
Kind of like a stored procedure
- Pure function
- Enables us to obtain a specific slice of data in the state tree.
- Memoized for performance
What is memoization?
An optimization technique to cache expensive function calls
- Tracks arguments
- Stores output
- Previous result is returned when argument match