Middle
What is a facade in NgRx, and what role does it play?
sobes.tech AI
Answer from AI
The facade in NgRx is a pattern that serves as an abstraction over the store, selectors, and actions. Its role is to simplify component interaction with the state, hide implementation details, and centralize state management logic.
Instead of each component directly subscribing to selectors and dispatching actions, the facade provides methods and properties that encapsulate these operations. This improves code readability, makes testing easier, and supports maintenance.
Example of a facade:
@Injectable({ providedIn: 'root' })
export class CounterFacade {
count$ = this.store.select(selectCount);
constructor(private store: Store) {}
increment() {
this.store.dispatch(increment());
}
decrement() {
this.store.dispatch(decrement());
}
reset() {
this.store.dispatch(reset());
}
}
The component uses the facade as follows:
@Component({ ... })
export class CounterComponent {
count$ = this.counterFacade.count$;
constructor(private counterFacade: CounterFacade) {}
onIncrement() {
this.counterFacade.increment();
}
onDecrement() {
this.counterFacade.decrement();
}
onReset() {
this.counterFacade.reset();
}
}