Managing Shared State
Dealing with shared state, at least at a basic level, is quite straight-forward with the reactive/observable based approach. Often there will be some data we want to be available in multiple places in the application. Consider the simple todo application we have already built. In that case, our state included an array of todos that we can add to. We created those todos in the HomeComponent
, but we also need access to the todos array in the DetailComponent
as well.
To deal with this, we created a service that looked like this:
@Injectable({
providedIn: 'root',
})
export class TodoService {
todos$ = new BehaviorSubject<Todo[]>([]);
addTodo(todo: Todo) {
const newTodos = [...this.todos$.value, todo];
this.todos$.next(newTodos);
}
getTodoById(id: string) {
return this.todos$.pipe(
map((todos) => todos.find((todo) => todo.id === id))
);
}
}