Skip to content

Commit 60c4aa4

Browse files
committed
feat(state): expose asReadOnly() when create state instance using functional approach
closes #1789
1 parent be8c438 commit 60c4aa4

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

libs/state/spec/rx-state.spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,31 @@ describe(rxState, () => {
379379
expect(accumulator).toHaveBeenCalled();
380380
});
381381
});
382+
383+
describe('asReadOnly', () => {
384+
it('should throw error when trying to call set from readOnlystate', () => {
385+
const { component } = setupComponent<{ count: number }>();
386+
387+
const readOnlyState = component.state.asReadOnly();
388+
389+
expect((): void => {
390+
readOnlyState['set'](
391+
'count',
392+
(state: { count: number }) => state.count + 1,
393+
);
394+
}).toThrowError('readOnlyState.set is not a function');
395+
});
396+
397+
it('should throw error when trying to call connect from readOnlystate', () => {
398+
const { component } = setupComponent<{ count: number }>();
399+
400+
const readOnlyState = component.state.asReadOnly();
401+
402+
expect((): void => {
403+
readOnlyState['connect']('count', of(10));
404+
}).toThrowError('readOnlyState.connect is not a function');
405+
});
406+
});
382407
});
383408

384409
type ITestComponent<State extends object> = {

libs/state/src/lib/rx-state.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@ export type RxState<T extends object> = Pick<
1212
| 'signal'
1313
| 'computed'
1414
| 'computedFrom'
15+
| 'asReadOnly'
1516
>;
1617

1718
export type RxStateSetupFn<State extends object> = (
1819
rxState: Pick<
1920
RxState<State>,
2021
'connect' | 'set' | 'get' | 'select' | 'setAccumulator'
21-
>
22+
>,
2223
) => void;
2324

2425
/**
@@ -46,7 +47,7 @@ export type RxStateSetupFn<State extends object> = (
4647
*
4748
*/
4849
export function rxState<State extends object>(
49-
setupFn?: RxStateSetupFn<State>
50+
setupFn?: RxStateSetupFn<State>,
5051
): RxState<State> {
5152
assertInInjectionContext(rxState);
5253

@@ -65,6 +66,7 @@ export function rxState<State extends object>(
6566
computedFrom: legacyState.computedFrom.bind(legacyState),
6667
$: legacyState.$,
6768
setAccumulator: legacyState.setAccumulator.bind(legacyState),
69+
asReadOnly: legacyState.asReadOnly.bind(legacyState),
6870
};
6971

7072
setupFn?.(state);

0 commit comments

Comments
 (0)