Skip to content

Commit 17d6f3a

Browse files
committed
Add signals
1 parent 985fabb commit 17d6f3a

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,15 @@ this.todoStore
101101

102102
The `select` method will only trigger an event if the value of the specific property of the state has been changed. In addition the returned values are deep copies of the values in the store, so it is can't cause any reference issues.
103103

104+
### Usage with signals
105+
106+
Since Angular 17, [Signals](https://angular.io/guide/signals#angular-signals) can be used instead of Observables. To achieve this, the function `selectAsSignal` can be used:
107+
108+
```ts
109+
// get a signal of a specific part of the state
110+
const myTodos = this.todoStore.selectAsSignal(state => state.todos);
111+
```
112+
104113
### Get state snapshot
105114

106115
Some operations only require the current state of the store and do not need to get notified about changes. These are cases where a snapshot of the latest state can be very helpful.

lib/src/store/store.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { inject } from '@angular/core';
1+
import { inject, Signal } from '@angular/core';
2+
import { toSignal } from '@angular/core/rxjs-interop';
23
import {
34
BehaviorSubject,
45
map,
@@ -19,7 +20,10 @@ export abstract class Store<State extends object> {
1920

2021
readonly state$: Observable<State>;
2122

22-
constructor(private name: string, initialState: State) {
23+
constructor(
24+
private name: string,
25+
initialState: State
26+
) {
2327
this.stateSource = new BehaviorSubject<State>(initialState);
2428
this.state$ = this.stateSource.asObservable();
2529
this.actionSource = new Subject<Action<State>>();
@@ -42,6 +46,14 @@ export abstract class Store<State extends object> {
4246
);
4347
}
4448

49+
selectAsSignal<SelectedState>(
50+
selector: (state: State) => SelectedState
51+
): Signal<SelectedState> {
52+
return toSignal(this.select(selector), {
53+
initialValue: selector(this.snapshot),
54+
});
55+
}
56+
4557
get snapshot() {
4658
return this.stateSource.getValue();
4759
}

0 commit comments

Comments
 (0)