From 8418cd18d3a903c6660c7b50d3a9367c4f1d3296 Mon Sep 17 00:00:00 2001
From: Michael Small <33669563+michael-small@users.noreply.github.com>
Date: Sat, 14 Nov 2026 10:45:01 -0600
Subject: [PATCH 1/3] feat: widen `withResource` to `Resource` beyond
`ResourceRef` (#301)
Approved by Rainer over DMs
---
.../src/lib/with-resource.spec.ts | 410 +++++++++++++++++-
libs/ngrx-toolkit/src/lib/with-resource.ts | 374 ++++++++++++----
.../tests/util/custom-extended-resources.ts | 54 +++
.../tests/util/resource-test-adapter.ts | 3 +
.../tests/util/setup-mapped-resource.ts | 3 +-
.../tests/util/setup-named-resource.ts | 4 +-
.../tests/util/setup-unnamed-resource.ts | 4 +-
.../lib/with-resource/tests/util/snapshot.ts | 26 ++
8 files changed, 783 insertions(+), 95 deletions(-)
create mode 100644 libs/ngrx-toolkit/src/lib/with-resource/tests/util/custom-extended-resources.ts
create mode 100644 libs/ngrx-toolkit/src/lib/with-resource/tests/util/snapshot.ts
diff --git a/libs/ngrx-toolkit/src/lib/with-resource.spec.ts b/libs/ngrx-toolkit/src/lib/with-resource.spec.ts
index 9d8bd12a..6b7df276 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource.spec.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource.spec.ts
@@ -3,7 +3,13 @@ import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
-import { Resource, resource, ResourceSnapshot, Signal } from '@angular/core';
+import {
+ Resource,
+ resource,
+ ResourceSnapshot,
+ signal,
+ Signal,
+} from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';
import { TestBed } from '@angular/core/testing';
import {
@@ -13,12 +19,22 @@ import {
withProps,
withState,
} from '@ngrx/signals';
-import { of } from 'rxjs';
+import { delay, of } from 'rxjs';
import { Assert, IsEqual, Satisfies } from './test-utils/types';
import { ErrorHandling, mapToResource, withResource } from './with-resource';
+import {
+ stuffExtendedResourceReadable,
+ stuffExtendedResourceWritable,
+} from './with-resource/tests/util/custom-extended-resources';
import { Address, venice, vienna } from './with-resource/tests/util/fixtures';
import { paramsForResourceTypes } from './with-resource/tests/util/params-for-resource-types';
import { setupUnnamedResource } from './with-resource/tests/util/setup-unnamed-resource';
+import { withPreviousValue } from './with-resource/tests/util/snapshot';
+
+import {
+ extendResource,
+ withPreviousValueOnLoading,
+} from '@ngrx/signals/resource';
describe('withResource', () => {
describe('standard tests', () => {
@@ -263,6 +279,237 @@ describe('withResource', () => {
});
});
+ describe('extra properties checks', () => {
+ describe('extra properties go to `props` so they cannot be written to', () => {
+ it('for unnamed writables', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => stuffExtendedResourceWritable(() => 'a')),
+ );
+
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.stuff()).toBe('a stuff');
+
+ // @ts-expect-error - extra properties should not be patchable
+ patchState(store, { stuff: 'b stuff' });
+ });
+ it('for unnamed readables', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => stuffExtendedResourceReadable(() => 'a')),
+ );
+
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.stuff()).toBe('a stuff');
+
+ // @ts-expect-error - extra properties should not be patchable
+ patchState(store, { stuff: 'b stuff' });
+ });
+ it('for named readables', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => ({
+ name: stuffExtendedResourceReadable(() => 'a'),
+ })),
+ );
+
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.nameStuff()).toBe('a stuff');
+
+ // @ts-expect-error - extra properties should not be patchable
+ patchState(store, { nameStuff: 'b stuff' });
+ });
+ it('for named writables', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => ({
+ name: stuffExtendedResourceWritable(() => 'a'),
+ })),
+ );
+
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.nameStuff()).toBe('a stuff');
+
+ // @ts-expect-error - extra properties should not be patchable
+ patchState(store, { nameStuff: 'b stuff' });
+ });
+ });
+ it('can call custom unnamed writable resource and extract custom extra signal properties', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => stuffExtendedResourceWritable(() => 'a')),
+ );
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.value()).toBe('a');
+ expect(store.stuff()).toBe('a stuff');
+
+ patchState(store, { value: 'b' });
+
+ expect(store.value()).toBe('b');
+ expect(store.stuff()).toBe('b stuff');
+ });
+ it('can call custom unnamed readable resource and extract custom extra signal properties', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => stuffExtendedResourceReadable(() => 'a')),
+ );
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.value()).toBe('a');
+ expect(store.stuff()).toBe('a stuff');
+
+ // @ts-expect-error - readable resources should not have their value patchable
+ patchState(store, { value: 'b' });
+
+ expect(store.value()).toBe('a');
+ expect(store.stuff()).toBe('a stuff');
+ });
+ it('can supply custom named resources (writable and unwritable) and extract custom extra signal properties', async () => {
+ const Store = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => ({
+ idWritable: stuffExtendedResourceWritable(() => 'a'),
+ idReadable: stuffExtendedResourceReadable(() => 'a'),
+ })),
+ );
+ const store = TestBed.inject(Store);
+
+ await wait();
+
+ expect(store.idWritableValue()).toBe('a');
+ expect(store.idReadableValue()).toBe('a');
+ expect(store.idWritableStuff()).toBe('a stuff');
+ expect(store.idReadableStuff()).toBe('a stuff');
+
+ patchState(store, { idWritableValue: 'b' });
+ // @ts-expect-error - readable resources should not have their value patchable
+ patchState(store, { idReadableValue: 'b' });
+
+ expect(store.idWritableValue()).toBe('b');
+ expect(store.idReadableValue()).toBe('a');
+ expect(store.idWritableStuff()).toBe('b stuff');
+ expect(store.idReadableStuff()).toBe('a stuff');
+ });
+
+ it('can supply custom unnamed (writable and unwritable) and custom named (writable and unwritable) and extract custom extra signal properties', async () => {
+ const UnnamedWritableAndNamedComboStore = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => stuffExtendedResourceWritable(() => 'a')),
+ withResource(() => ({
+ idWritable: stuffExtendedResourceWritable(() => 'a'),
+ idReadable: stuffExtendedResourceReadable(() => 'a'),
+ })),
+ );
+ const unnamedWritableAndNamedComboStore = TestBed.inject(
+ UnnamedWritableAndNamedComboStore,
+ );
+
+ await wait();
+
+ expect(unnamedWritableAndNamedComboStore.value()).toBe('a');
+ expect(unnamedWritableAndNamedComboStore.stuff()).toBe('a stuff');
+ expect(unnamedWritableAndNamedComboStore.idWritableValue()).toBe('a');
+ expect(unnamedWritableAndNamedComboStore.idReadableValue()).toBe('a');
+ expect(unnamedWritableAndNamedComboStore.idWritableStuff()).toBe(
+ 'a stuff',
+ );
+ expect(unnamedWritableAndNamedComboStore.idReadableStuff()).toBe(
+ 'a stuff',
+ );
+
+ patchState(unnamedWritableAndNamedComboStore, {
+ idWritableValue: 'b',
+ });
+ patchState(unnamedWritableAndNamedComboStore, { value: 'b' });
+ patchState(unnamedWritableAndNamedComboStore, {
+ // @ts-expect-error - readable resources should not have their value patchable
+ idReadableValue: 'b',
+ });
+
+ expect(unnamedWritableAndNamedComboStore.value()).toBe('b');
+ expect(unnamedWritableAndNamedComboStore.stuff()).toBe('b stuff');
+ expect(unnamedWritableAndNamedComboStore.idWritableValue()).toBe('b');
+ expect(unnamedWritableAndNamedComboStore.idReadableValue()).toBe('a');
+ expect(unnamedWritableAndNamedComboStore.idWritableStuff()).toBe(
+ 'b stuff',
+ );
+ expect(unnamedWritableAndNamedComboStore.idReadableStuff()).toBe(
+ 'a stuff',
+ );
+
+ const UnnamedUnwritableAndNamedComboStore = signalStore(
+ { providedIn: 'root', protectedState: false },
+ withResource(() => stuffExtendedResourceReadable(() => 'a')),
+ withResource(() => ({
+ idWritable: stuffExtendedResourceWritable(() => 'a'),
+ idReadable: stuffExtendedResourceReadable(() => 'a'),
+ })),
+ );
+ const unnamedUnwritableAndNamedComboStore = TestBed.inject(
+ UnnamedUnwritableAndNamedComboStore,
+ );
+
+ await wait();
+
+ expect(unnamedUnwritableAndNamedComboStore.value()).toBe('a');
+ expect(unnamedUnwritableAndNamedComboStore.stuff()).toBe('a stuff');
+ expect(unnamedUnwritableAndNamedComboStore.idWritableValue()).toBe(
+ 'a',
+ );
+ expect(unnamedUnwritableAndNamedComboStore.idReadableValue()).toBe(
+ 'a',
+ );
+ expect(unnamedUnwritableAndNamedComboStore.idWritableStuff()).toBe(
+ 'a stuff',
+ );
+ expect(unnamedUnwritableAndNamedComboStore.idReadableStuff()).toBe(
+ 'a stuff',
+ );
+
+ patchState(unnamedUnwritableAndNamedComboStore, {
+ idWritableValue: 'b',
+ });
+ // @ts-expect-error - readable resources should not have their value patchable
+ patchState(unnamedUnwritableAndNamedComboStore, { value: 'b' });
+ patchState(unnamedUnwritableAndNamedComboStore, {
+ // @ts-expect-error - readable resources should not have their value patchable
+ idReadableValue: 'b',
+ });
+
+ expect(unnamedUnwritableAndNamedComboStore.value()).toBe('a');
+ expect(unnamedUnwritableAndNamedComboStore.stuff()).toBe('a stuff');
+ expect(unnamedUnwritableAndNamedComboStore.idWritableValue()).toBe(
+ 'b',
+ );
+ expect(unnamedUnwritableAndNamedComboStore.idReadableValue()).toBe(
+ 'a',
+ );
+ expect(unnamedUnwritableAndNamedComboStore.idWritableStuff()).toBe(
+ 'b stuff',
+ );
+ expect(unnamedUnwritableAndNamedComboStore.idReadableStuff()).toBe(
+ 'a stuff',
+ );
+ });
+ });
+
describe('override protection', () => {
const warningSpy = jest.spyOn(console, 'warn');
@@ -312,6 +559,33 @@ describe('withResource', () => {
'userValue',
);
});
+
+ //TODO wait for https://github.com/ngrx/platform/pull/4932 and then add 'value' to the list
+ it.each([
+ 'status',
+ 'error',
+ 'isLoading',
+ '_reload',
+ 'hasValue',
+ 'stuff',
+ ])(
+ `warns if %s is not a member of the store with a custom extended resource`,
+ (memberName) => {
+ const Store = signalStore(
+ { providedIn: 'root' },
+ withProps(() => ({ [memberName]: true })),
+ withResource(() => stuffExtendedResourceWritable(() => 'a')),
+ );
+
+ TestBed.inject(Store);
+
+ expect(warningSpy).toHaveBeenCalledWith(
+ '@ngrx/signals: SignalStore members cannot be overridden.',
+ 'Trying to override:',
+ memberName,
+ );
+ },
+ );
});
it('works also with list/detail use case', async () => {
@@ -319,12 +593,14 @@ describe('withResource', () => {
{ providedIn: 'root', protectedState: false },
withState({ id: undefined as number | undefined }),
withResource(({ id }) => ({
- list: httpResource<{ id: number; name: string }[]>(
- () => '/address',
+ list: httpResource<
{
- defaultValue: [],
- },
- ),
+ id: number;
+ name: string;
+ }[]
+ >(() => '/address', {
+ defaultValue: [],
+ }),
detail: httpResource
(() =>
id() ? `/address/${id()}` : undefined,
),
@@ -798,6 +1074,77 @@ describe('withResource', () => {
IsEqual>
>;
});
+ it('only exposes reload methods for reloadable resources', () => {
+ const Store = signalStore(
+ { providedIn: 'root' },
+ withResource(() => ({
+ digit: resource({
+ loader: () => Promise.resolve(-1),
+ defaultValue: 0,
+ }),
+ digitSnapshotted: withPreviousValue(
+ resource({
+ loader: () => Promise.resolve(-1),
+ defaultValue: 0,
+ }),
+ ),
+ })),
+ withResource(() =>
+ resource({
+ loader: () => Promise.resolve(-1),
+ defaultValue: 0,
+ }),
+ ),
+ withMethods((store) => ({
+ namedReload: () => store._digitReload(),
+ unnamedReload: () => store._reload(),
+ // @ts-expect-error - a snapshot should not have a reload
+ invalidReload: () => store._digitSnapshottedReload(),
+ })),
+ );
+
+ const _store = TestBed.inject(Store);
+
+ type _T1 = Assert boolean>>;
+ type _T2 = Assert boolean>>;
+ });
+
+ describe('patchState restrictions do not allow patching', () => {
+ it('an unnamed non-reloadable resource value', () => {
+ signalStore(
+ withResource(() =>
+ withPreviousValue(
+ resource({
+ loader: () => Promise.resolve(1),
+ defaultValue: 0,
+ }),
+ ),
+ ),
+ withMethods((store) => ({
+ // @ts-expect-error - non-reloadable Resource values are not state
+ setValue: (value: number) => patchState(store, { value }),
+ })),
+ );
+ });
+
+ it('a named non-reloadable resource value', () => {
+ signalStore(
+ withResource(() => ({
+ digitSnapshotted: withPreviousValue(
+ resource({
+ loader: () => Promise.resolve(-1),
+ defaultValue: 0,
+ }),
+ ),
+ })),
+ withMethods((store) => ({
+ setNamedValue: (value: number) =>
+ // @ts-expect-error digitSnapshotted is a `Resource` value, but not state, so it should not be patchable
+ patchState(store, { digitSnapshottedValue: value }),
+ })),
+ );
+ });
+ });
describe('mapToResource', () => {
it('satisfies the Resource interface without default value', () => {
@@ -947,4 +1294,53 @@ describe('withResource', () => {
);
});
});
+
+ describe('supports resource extensions', () => {
+ const wait = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
+ describe('withPreviousValueOnLoading', () => {
+ it('retains previous value of loading', async () => {
+ const stuff = signal(0);
+ const Store = signalStore(
+ { providedIn: 'root' },
+ withResource(() => ({
+ id: extendResource(
+ rxResource({
+ params: () => stuff(),
+ stream: ({ params }) => of(params).pipe(delay(2)),
+ defaultValue: 0,
+ }),
+ withPreviousValueOnLoading(),
+ ),
+ })),
+ );
+ const store = TestBed.inject(Store);
+ const value = store.idValue;
+ expect(value()).toBe(0);
+ stuff.set(1);
+ expect(store.idIsLoading()).toBe(true);
+ expect(value()).toBe(0);
+ await wait(100);
+ expect(store.idIsLoading()).toBe(false);
+ expect(value()).toBe(1);
+
+ // TODO - on extensions branch, comment this in
+ // type _T1 = Assert>>;
+ });
+ });
+ // describe('withValueOnLoading', () => {
+ // it('', () => {
+ // expect(true).toBe(false);
+ // });
+ // });
+ // describe('withPreviousValueOnLoading', () => {
+ // it('', () => {
+ // expect(true).toBe(false);
+ // });
+ // });
+ // describe('withValueOnError', () => {
+ // it('', () => {
+ // expect(true).toBe(false);
+ // });
+ // });
+ });
});
diff --git a/libs/ngrx-toolkit/src/lib/with-resource.ts b/libs/ngrx-toolkit/src/lib/with-resource.ts
index 95cf6cec..5047baec 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource.ts
@@ -1,5 +1,6 @@
//** Types for `withResource` */
+import { HttpResourceRef } from '@angular/common/http';
import {
isSignal,
Resource,
@@ -58,33 +59,154 @@ export type ResourceResult = {
hasValue: >(
this: Original,
) => this is Resource> & Original;
+ };
+};
+export type ResourceRefResult = {
+ state: { value: T };
+ props: {
+ status: Signal;
+ error: Signal;
+ isLoading: Signal;
+ snapshot: Signal>;
+ };
+ methods: {
+ hasValue: >(
+ this: Original,
+ ) => this is ResourceRef> & Original;
_reload(): boolean;
};
};
-export type ResourceDictionary = Record>;
+type ReloadableResource = ResourceRef | HttpResourceRef;
+
+type ResourceCoreKeys =
+ | 'value'
+ | 'status'
+ | 'error'
+ | 'isLoading'
+ | 'snapshot'
+ | 'hasValue';
+
+type AdditionalSignalProps> = {
+ [Prop in keyof T as Prop extends ResourceCoreKeys
+ ? never
+ : T[Prop] extends Signal
+ ? Prop
+ : never]: T[Prop];
+};
+
+type InferResourceValue> =
+ T['value'] extends Signal ? S : never;
+
+type ConditionalReloadMethod> =
+ T extends ReloadableResource
+ ? { _reload(): boolean }
+ : Record;
+
+declare const NON_PATCHABLE_RESOURCE_STATE: unique symbol;
+
+type NonPatchableResourceStateMarker = {
+ [NON_PATCHABLE_RESOURCE_STATE]?: never;
+};
+
+type ResourceValueType<
+ T extends Resource,
+ HasUndefinedErrorHandling extends boolean,
+> = HasUndefinedErrorHandling extends true
+ ? InferResourceValue | undefined
+ : InferResourceValue;
+
+type UnnamedResourceResult<
+ T extends Resource,
+ HasUndefinedErrorHandling extends boolean,
+> = {
+ state: T extends ReloadableResource
+ ? {
+ value: ResourceValueType;
+ }
+ : NonPatchableResourceStateMarker;
+ props: (T extends ReloadableResource
+ ? Record
+ : {
+ value: Signal>;
+ }) & {
+ status: Signal;
+ error: Signal;
+ isLoading: Signal;
+ snapshot: Signal>>;
+ } & AdditionalSignalProps;
+ methods: {
+ hasValue: <
+ Original extends {
+ value: Signal>;
+ },
+ >(
+ this: Original,
+ ) => this is {
+ value: Signal, undefined>>;
+ } & Original;
+ } & ConditionalReloadMethod;
+};
+
+export type ResourceDictionary = Record>;
+
+// Without this, only one resource would be able to have its additional signal props extracted
+// When there are two or more named resources,
+// neither additional property can be indexed for certain,
+// because it would be a union of the two's additional properties,
+// and TS cannot pick the correct one when indexing into it.
+// So there would be no resolution of a particular resource's additional property.
+// This type util makes this type mapping an intersection, so all additional properties
+// of all resources are preserved, but also can be indexed for a particular resource.
+// https://stackoverflow.com/a/50375286 explanation, with relevant TS doc links
+type UnionToIntersection = (
+ T extends unknown ? (arg: T) => void : never
+) extends (arg: infer R) => void
+ ? R
+ : Record;
+
+type NamedAdditionalSignalProps =
+ UnionToIntersection<
+ {
+ [ResourceName in keyof T & string]: {
+ [Prop in keyof AdditionalSignalProps &
+ string as `${ResourceName}${Capitalize}`]: AdditionalSignalProps<
+ T[ResourceName]
+ >[Prop];
+ };
+ }[keyof T & string]
+ >;
export type NamedResourceResult<
T extends ResourceDictionary,
HasUndefinedErrorHandling extends boolean,
> = {
state: {
- [Prop in keyof T as `${Prop &
- string}Value`]: T[Prop]['value'] extends Signal
- ? HasUndefinedErrorHandling extends true
- ? S | undefined
- : S
+ [Prop in keyof T as T[Prop] extends ReloadableResource
+ ? `${Prop & string}Value`
+ : never]: T[Prop] extends Resource
+ ? ResourceValueType
: never;
- };
+ } & NonPatchableResourceStateMarker;
props: {
+ [Prop in keyof T as T[Prop] extends ReloadableResource
+ ? never
+ : `${Prop & string}Value`]: Signal<
+ T[Prop] extends Resource
+ ? ResourceValueType
+ : never
+ >;
+ } & {
[Prop in keyof T as `${Prop & string}Status`]: Signal;
} & {
[Prop in keyof T as `${Prop & string}Error`]: Signal;
} & {
[Prop in keyof T as `${Prop & string}IsLoading`]: Signal;
} & {
- [Prop in keyof T as `${Prop & string}Snapshot`]: T[Prop]['snapshot'];
- };
+ [Prop in keyof T as `${Prop & string}Snapshot`]: Signal<
+ ResourceSnapshot ? S : never>
+ >;
+ } & NamedAdditionalSignalProps;
methods: {
[Prop in keyof T as `${Prop & string}HasValue`]: <
Original extends Record<
@@ -107,7 +229,9 @@ export type NamedResourceResult<
> &
Original;
} & {
- [Prop in keyof T as `_${Prop & string}Reload`]: () => boolean;
+ [Prop in keyof T as T[Prop] extends ReloadableResource
+ ? `_${Prop & string}Reload`
+ : never]: () => boolean;
};
};
@@ -130,10 +254,13 @@ const defaultOptions: Required = {
* Integrates a `Resource` into the SignalStore and makes the store instance
* implement the `Resource` interface.
*
- * The resource's value is stored under the `value` key in the state
- * and is exposed as a `DeepSignal`.
+ * Reloadable resources (`ResourceRef`/`HttpResourceRef`) expose their
+ * value under `value` in the store state and can be updated via `patchState`.
*
- * It can also be updated via `patchState`.
+ * Plain `Resource` values are exposed as signals on the store instance,
+ * but are not part of state and therefore cannot be changed via `patchState`.
+ * Additional signal members on the resource (for example `foo`) are also
+ * exposed on the store as props.
*
* @usageNotes
*
@@ -157,32 +284,32 @@ const defaultOptions: Required = {
*/
export function withResource<
Input extends SignalStoreFeatureResult,
- ResourceValue,
+ ResourceType extends Resource,
>(
resourceFactory: (
store: Input['props'] & Input['methods'] & StateSignals,
- ) => ResourceRef,
-): SignalStoreFeature>;
+ ) => ResourceType,
+): SignalStoreFeature>;
export function withResource<
Input extends SignalStoreFeatureResult,
- ResourceValue,
+ ResourceType extends Resource,
>(
resourceFactory: (
store: Input['props'] & Input['methods'] & StateSignals,
- ) => ResourceRef,
+ ) => ResourceType,
resourceOptions: { errorHandling: 'undefined value' },
-): SignalStoreFeature>;
+): SignalStoreFeature>;
export function withResource<
Input extends SignalStoreFeatureResult,
- ResourceValue,
+ ResourceType extends Resource,
>(
resourceFactory: (
store: Input['props'] & Input['methods'] & StateSignals,
- ) => ResourceRef,
+ ) => ResourceType,
resourceOptions?: ResourceOptions,
-): SignalStoreFeature>;
+): SignalStoreFeature>;
/**
* @experimental
@@ -192,9 +319,13 @@ export function withResource<
* registered by name, which is used as a prefix when spreading the members
* of `Resource` onto the store.
*
- * Each resource’s value is part of the state, stored under the `value` key
- * with the resource name as prefix. Values are exposed as `DeepSignal`s and
- * can be updated via `patchState`.
+ * Reloadable resources (`ResourceRef`/`HttpResourceRef`) place their values
+ * in state using `Value` keys and support updates via `patchState`.
+ *
+ * Plain `Resource` values are exposed as read-only signals with `Value`
+ * but are not stored in state.
+ * Additional signal members are exposed as read-only props using
+ * ``.
*
* @usageNotes
*
@@ -215,7 +346,7 @@ export function withResource<
* ```
*
* @param resourceFactory A factory function that receives the store's props,
- * methods, and state signals. It must return a `Record`.
+ * methods, and state signals. It must return a `Record`.
* @param resourceOptions Allows to configure the error handling behavior.
*/
export function withResource<
@@ -253,7 +384,7 @@ export function withResource<
>(
resourceFactory: (
store: Input['props'] & Input['methods'] & StateSignals,
- ) => ResourceRef | ResourceDictionary,
+ ) => Resource | ResourceDictionary,
resourceOptions?: ResourceOptions,
): SignalStoreFeature {
const options: Required = {
@@ -267,7 +398,10 @@ export function withResource<
...store.methods,
});
- if (isResourceRef(resourceOrDictionary)) {
+ if (
+ isResourceRef(resourceOrDictionary) ||
+ isResource(resourceOrDictionary)
+ ) {
return createUnnamedResource(
resourceOrDictionary,
options.errorHandling,
@@ -282,27 +416,44 @@ export function withResource<
}
function createUnnamedResource(
- resource: ResourceRef,
+ resource: Resource,
errorHandling: ErrorHandling,
) {
function hasValue(): this is Resource> {
- return resource.hasValue();
+ if (isResourceRef(resource)) {
+ return resource.hasValue();
+ } else {
+ return resource.hasValue();
+ }
+ }
+
+ const metadataProps = {
+ status: resource.status,
+ error: resource.error,
+ isLoading: resource.isLoading,
+ snapshot: resource.snapshot,
+ ...extractAdditionalSignalProps(resource),
+ };
+
+ if (isResourceRef(resource)) {
+ return signalStoreFeature(
+ withLinkedState(() => ({
+ value: valueSignalForErrorHandling(resource, errorHandling),
+ })),
+ withProps(() => metadataProps),
+ withMethods(() => ({
+ hasValue,
+ _reload: () => resource.reload(),
+ })),
+ );
}
return signalStoreFeature(
- withLinkedState(() => ({
- value: valueSignalForErrorHandling(resource, errorHandling),
- })),
withProps(() => ({
- status: resource.status,
- error: resource.error,
- isLoading: resource.isLoading,
- snapshot: resource.snapshot,
- })),
- withMethods(() => ({
- hasValue,
- _reload: () => resource.reload(),
+ value: valueSignalForErrorHandling(resource, errorHandling),
+ ...metadataProps,
})),
+ withMethods(() => ({ hasValue })),
);
}
@@ -312,38 +463,42 @@ function createNamedResource(
) {
const keys = Object.keys(dictionary);
- const state: Record> = keys.reduce(
- (state, resourceName) => ({
- ...state,
- [`${resourceName}Value`]: valueSignalForErrorHandling(
- dictionary[resourceName],
+ const state: Record> = {};
+ const props: Record> = {};
+ const methods: Record boolean> = {};
+
+ for (const resourceName of keys) {
+ const res = dictionary[resourceName];
+
+ props[`${resourceName}Status`] = res.status;
+ props[`${resourceName}Error`] = res.error;
+ props[`${resourceName}IsLoading`] = res.isLoading;
+ props[`${resourceName}Snapshot`] = res.snapshot;
+ assignPrefixedProps(props, resourceName, extractAdditionalSignalProps(res));
+ methods[`${resourceName}HasValue`] = isResourceRef(res)
+ ? () => res.hasValue()
+ : () => res.hasValue();
+
+ if (isResourceRef(res)) {
+ state[`${resourceName}Value`] = valueSignalForErrorHandling(
+ res,
errorHandling,
- ),
- }),
- {},
- );
-
- const props: Record> = keys.reduce(
- (props, resourceName) => ({
- ...props,
- [`${resourceName}Status`]: dictionary[resourceName].status,
- [`${resourceName}Error`]: dictionary[resourceName].error,
- [`${resourceName}IsLoading`]: dictionary[resourceName].isLoading,
- [`${resourceName}Snapshot`]: dictionary[resourceName].snapshot,
- }),
- {},
- );
+ ) as WritableSignal;
+ methods[`_${resourceName}Reload`] = () => res.reload();
+ } else {
+ props[`${resourceName}Value`] = valueSignalForErrorHandling(
+ res,
+ errorHandling,
+ );
+ }
+ }
- const methods: Record boolean> = keys.reduce(
- (methods, resourceName) => {
- return {
- ...methods,
- [`${resourceName}HasValue`]: () => dictionary[resourceName].hasValue(),
- [`_${resourceName}Reload`]: () => dictionary[resourceName].reload(),
- };
- },
- {},
- );
+ if (Object.keys(state).length === 0) {
+ return signalStoreFeature(
+ withProps(() => props),
+ withMethods(() => methods),
+ );
+ }
return signalStoreFeature(
withLinkedState(() => state),
@@ -352,7 +507,7 @@ function createNamedResource(
);
}
-export function isResourceRef(value: unknown): value is ResourceRef {
+export function isResource(value: unknown): value is Resource {
return (
value !== null &&
typeof value === 'object' &&
@@ -361,12 +516,69 @@ export function isResourceRef(value: unknown): value is ResourceRef {
'status' in value &&
'error' in value &&
'isLoading' in value &&
- 'hasValue' in value &&
+ 'snapshot' in value &&
+ 'hasValue' in value
+ );
+}
+
+export function isResourceRef(value: unknown): value is ResourceRef {
+ return (
+ isResource(value) &&
'reload' in value &&
- 'snapshot' in value
+ 'set' in value &&
+ 'update' in value &&
+ 'asReadonly' in value
+ );
+}
+
+function extractAdditionalSignalProps(
+ resource: Resource,
+): Record> {
+ const additionalSignals: Record> = {};
+
+ for (const key of Object.keys(resource)) {
+ if (isResourceCoreKey(key)) {
+ continue;
+ }
+
+ const candidate = (resource as unknown as Record)[key];
+ if (isSignal(candidate)) {
+ additionalSignals[key] = candidate;
+ }
+ }
+
+ return additionalSignals;
+}
+
+function isResourceCoreKey(key: string): key is ResourceCoreKeys {
+ return (
+ key === 'value' ||
+ key === 'status' ||
+ key === 'error' ||
+ key === 'isLoading' ||
+ key === 'snapshot' ||
+ key === 'hasValue'
);
}
+function assignPrefixedProps(
+ target: Record>,
+ resourceName: string,
+ source: Record>,
+): void {
+ for (const key of Object.keys(source)) {
+ target[`${resourceName}${capitalizeKey(key)}`] = source[key];
+ }
+}
+
+function capitalizeKey(value: string): string {
+ if (value.length === 0) {
+ return value;
+ }
+
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
//** Types for `mapToResource` */
type NamedResource = {
@@ -429,7 +641,7 @@ type MappedResource<
*
* @param store The store instance to map the resource to.
* @param name The name of the resource to map.
- * @returns `ResourceRef`
+ * @returns `Resource`
*/
export function mapToResource<
Name extends ResourceNames,
@@ -519,19 +731,19 @@ export function mapToResource<
* a breaking change.
*/
function valueSignalForErrorHandling(
- res: ResourceRef,
+ res: Resource,
errorHandling: 'undefined value',
-): WritableSignal;
+): Signal;
function valueSignalForErrorHandling(
- res: ResourceRef,
+ res: Resource,
errorHandling: ErrorHandling,
-): WritableSignal;
+): Signal;
function valueSignalForErrorHandling(
- res: ResourceRef,
+ res: Resource,
errorHandling: ErrorHandling,
-): WritableSignal {
+): Signal {
const originalSignal = res.value;
switch (errorHandling) {
diff --git a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/custom-extended-resources.ts b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/custom-extended-resources.ts
new file mode 100644
index 00000000..469991b3
--- /dev/null
+++ b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/custom-extended-resources.ts
@@ -0,0 +1,54 @@
+import { computed, Resource, ResourceRef, Signal } from '@angular/core';
+import { rxResource } from '@angular/core/rxjs-interop';
+import { of } from 'rxjs';
+
+export function stuffExtendedResourceWritable(
+ params?: () => string | undefined,
+): ResourceRef & { stuff: Signal } {
+ const resource = rxResource({
+ params: () => params?.() ?? '',
+ stream: ({ params }) => {
+ return of(params);
+ },
+ });
+
+ const stuff = computed(() => resource.value() + ' stuff');
+
+ return {
+ stuff,
+ value: resource.value,
+ status: resource.status,
+ error: resource.error,
+ isLoading: resource.isLoading,
+ snapshot: resource.snapshot,
+ hasValue: resource.hasValue,
+ set: resource.set.bind(resource),
+ update: resource.update.bind(resource),
+ asReadonly: resource.asReadonly.bind(resource),
+ reload: resource.reload.bind(resource),
+ destroy: resource.destroy.bind(resource),
+ };
+}
+
+export function stuffExtendedResourceReadable(
+ params?: () => string | undefined,
+): Resource & { stuff: Signal } {
+ const resource = rxResource({
+ params: () => params?.() ?? '',
+ stream: ({ params }) => {
+ return of(params);
+ },
+ }).asReadonly();
+
+ const stuff = computed(() => resource.value() + ' stuff');
+
+ return {
+ stuff,
+ value: resource.value,
+ status: resource.status,
+ error: resource.error,
+ isLoading: resource.isLoading,
+ snapshot: resource.snapshot,
+ hasValue: resource.hasValue.bind(resource),
+ };
+}
diff --git a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/resource-test-adapter.ts b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/resource-test-adapter.ts
index d0cc9457..f874c9bb 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/resource-test-adapter.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/resource-test-adapter.ts
@@ -12,5 +12,8 @@ export type ResourceTestAdapter = {
isLoading: boolean;
hasValue: boolean;
};
+};
+
+export type ReloadableResourceTestAdapter = ResourceTestAdapter & {
reload: () => void;
};
diff --git a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-mapped-resource.ts b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-mapped-resource.ts
index 6f0af070..bc015ba5 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-mapped-resource.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-mapped-resource.ts
@@ -9,7 +9,7 @@ import { setupNamedResource } from './setup-named-resource';
export function setupMappedResource(
errorHandling: ErrorHandling,
): ResourceTestAdapter {
- const { addressResolver, setId, setValue, reload, store } =
+ const { addressResolver, setId, setValue, store } =
setupNamedResource(errorHandling);
const resource = mapToResource(
@@ -28,6 +28,5 @@ export function setupMappedResource(
isLoading: resource.isLoading(),
hasValue: resource.hasValue(),
}),
- reload,
};
}
diff --git a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-named-resource.ts b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-named-resource.ts
index 2dc4a969..ca5f1858 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-named-resource.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-named-resource.ts
@@ -1,6 +1,6 @@
import { inject, resource } from '@angular/core';
import { TestBed } from '@angular/core/testing';
-import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
+import { patchState, signalStore, withState } from '@ngrx/signals';
import { ErrorHandling, withResource } from '../../../with-resource';
import { Address, AddressResolver, venice } from './fixtures';
import { ResourceTestAdapter } from './resource-test-adapter';
@@ -27,7 +27,6 @@ export function setupNamedResource(
},
{ errorHandling },
),
- withMethods((store) => ({ reload: () => store._addressReload() })),
);
TestBed.configureTestingModule({
@@ -54,6 +53,5 @@ export function setupNamedResource(
isLoading: store.addressIsLoading(),
hasValue: store.addressHasValue(),
}),
- reload: () => store.reload(),
};
}
diff --git a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-unnamed-resource.ts b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-unnamed-resource.ts
index 0939d10d..c3b075cb 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-unnamed-resource.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/setup-unnamed-resource.ts
@@ -3,11 +3,11 @@ import { TestBed } from '@angular/core/testing';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
import { ErrorHandling, withResource } from '../../../with-resource';
import { Address, AddressResolver, venice } from './fixtures';
-import { ResourceTestAdapter } from './resource-test-adapter';
+import { ReloadableResourceTestAdapter } from './resource-test-adapter';
export function setupUnnamedResource(
errorHandling?: ErrorHandling,
-): ResourceTestAdapter {
+): ReloadableResourceTestAdapter {
const addressResolver = {
resolve: jest.fn(() => Promise.resolve(venice)),
};
diff --git a/libs/ngrx-toolkit/src/lib/with-resource/tests/util/snapshot.ts b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/snapshot.ts
new file mode 100644
index 00000000..57829184
--- /dev/null
+++ b/libs/ngrx-toolkit/src/lib/with-resource/tests/util/snapshot.ts
@@ -0,0 +1,26 @@
+import {
+ linkedSignal,
+ Resource,
+ resourceFromSnapshots,
+ ResourceSnapshot,
+} from '@angular/core';
+
+export function withPreviousValue(input: Resource): Resource {
+ const derived = linkedSignal, ResourceSnapshot>({
+ source: input.snapshot,
+ computation: (snap, previous) => {
+ if (
+ snap.status === 'loading' &&
+ previous &&
+ previous.value.status !== 'error'
+ ) {
+ // When the input resource enters loading state, we keep the value
+ // from its previous state, if any.
+ return { status: 'loading' as const, value: previous.value.value };
+ }
+ // Otherwise we simply forward the state of the input resource.
+ return snap;
+ },
+ });
+ return resourceFromSnapshots(derived);
+}
From 0baac781905fbf2f7db95b603ec8700b4a33c19a Mon Sep 17 00:00:00 2001
From: Michael Small
Date: Sun, 25 Oct 2026 12:41:05 -0500
Subject: [PATCH 2/3] chore: expose resource w/o set/update as prop
---
.husky/commit-msg | 2 +-
.vscode/tasks.json | 28 +++++++++
.../src/lib/with-resource.spec.ts | 62 +++++++++++++++++++
libs/ngrx-toolkit/src/lib/with-resource.ts | 34 ++++++++--
4 files changed, 119 insertions(+), 7 deletions(-)
create mode 100644 .vscode/tasks.json
diff --git a/.husky/commit-msg b/.husky/commit-msg
index e0f5e42b..c643e2ac 100755
--- a/.husky/commit-msg
+++ b/.husky/commit-msg
@@ -1,2 +1,2 @@
-pnpm --no -- commitlint --edit ${1}
+pnpm exec commitlint --edit "$1"
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 00000000..bed50e08
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,28 @@
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "label": "Run ngrx-toolkit build",
+ "type": "shell",
+ "command": "pnpm",
+ "args": ["nx", "build", "ngrx-toolkit", "--skip-nx-cache"],
+ "isBackground": false,
+ "problemMatcher": []
+ },
+ {
+ "label": "Run ngrx-toolkit tests",
+ "type": "shell",
+ "command": "pnpm",
+ "args": [
+ "nx",
+ "test",
+ "ngrx-toolkit",
+ "--runInBand",
+ "--runTestsByPath",
+ "libs/ngrx-toolkit/src/lib/with-resource.spec.ts"
+ ],
+ "isBackground": false,
+ "problemMatcher": []
+ }
+ ]
+}
diff --git a/libs/ngrx-toolkit/src/lib/with-resource.spec.ts b/libs/ngrx-toolkit/src/lib/with-resource.spec.ts
index 6b7df276..580a0bad 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource.spec.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource.spec.ts
@@ -397,17 +397,76 @@ describe('withResource', () => {
expect(store.idReadableValue()).toBe('a');
expect(store.idWritableStuff()).toBe('a stuff');
expect(store.idReadableStuff()).toBe('a stuff');
+ expect(store.idWritable.value()).toBe('a');
+ expect(store.idWritableStuff()).toBe(store.idWritable.stuff());
+
+ type _WritableResourceValue = Assert<
+ IsEqual>
+ >;
+ type _ReadableResource = Assert<
+ IsEqual<
+ typeof store.idReadable,
+ ReturnType
+ >
+ >;
+ type _Reload = Assert<
+ IsEqual boolean>
+ >;
+ type _NoSet = Assert<
+ IsEqual<
+ 'set' extends keyof typeof store.idWritable ? true : false,
+ false
+ >
+ >;
+ type _NoUpdate = Assert<
+ IsEqual<
+ 'update' extends keyof typeof store.idWritable ? true : false,
+ false
+ >
+ >;
+ type _NoWritableValue = Assert<
+ IsEqual<
+ 'set' extends keyof typeof store.idWritable.value ? true : false,
+ false
+ >
+ >;
patchState(store, { idWritableValue: 'b' });
// @ts-expect-error - readable resources should not have their value patchable
patchState(store, { idReadableValue: 'b' });
expect(store.idWritableValue()).toBe('b');
+ expect(store.idWritable.value()).toBe('b');
expect(store.idReadableValue()).toBe('a');
expect(store.idWritableStuff()).toBe('b stuff');
expect(store.idReadableStuff()).toBe('a stuff');
});
+ it('preserves reload on custom named resources', () => {
+ const Store = signalStore(
+ { providedIn: 'root' },
+ withResource(() => ({
+ custom: {
+ ...stuffExtendedResourceReadable(() => 'a'),
+ reload: (): boolean => true,
+ },
+ })),
+ );
+ const store = TestBed.inject(Store);
+
+ expect(store.custom.reload()).toBe(true);
+
+ type _CustomReload = Assert<
+ IsEqual boolean>
+ >;
+ type _CustomStuff = Assert<
+ IsEqual<
+ typeof store.custom.stuff,
+ ReturnType['stuff']
+ >
+ >;
+ });
+
it('can supply custom unnamed (writable and unwritable) and custom named (writable and unwritable) and extract custom extra signal properties', async () => {
const UnnamedWritableAndNamedComboStore = signalStore(
{ providedIn: 'root', protectedState: false },
@@ -1064,6 +1123,7 @@ describe('withResource', () => {
);
const _store = TestBed.inject(Store);
+ const _digitResource: Resource = _store.digit;
type _T1 = Assert>>;
type _T2 = Assert<
@@ -1073,6 +1133,8 @@ describe('withResource', () => {
type _T4 = Assert<
IsEqual>
>;
+ type _T5 = Assert>>;
+ type _T6 = Assert boolean>>;
});
it('only exposes reload methods for reloadable resources', () => {
const Store = signalStore(
diff --git a/libs/ngrx-toolkit/src/lib/with-resource.ts b/libs/ngrx-toolkit/src/lib/with-resource.ts
index 5047baec..94f06afd 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource.ts
@@ -2,6 +2,7 @@
import { HttpResourceRef } from '@angular/common/http';
import {
+ computed,
isSignal,
Resource,
ResourceRef,
@@ -98,6 +99,11 @@ type AdditionalSignalProps> = {
type InferResourceValue> =
T['value'] extends Signal ? S : never;
+type NamedResourceProp> =
+ T extends ResourceRef
+ ? Omit & Resource
+ : T;
+
type ConditionalReloadMethod> =
T extends ReloadableResource
? { _reload(): boolean }
@@ -189,6 +195,8 @@ export type NamedResourceResult<
: never;
} & NonPatchableResourceStateMarker;
props: {
+ [Prop in keyof T]: NamedResourceProp;
+ } & {
[Prop in keyof T as T[Prop] extends ReloadableResource
? never
: `${Prop & string}Value`]: Signal<
@@ -321,6 +329,9 @@ export function withResource<
*
* Reloadable resources (`ResourceRef`/`HttpResourceRef`) place their values
* in state using `Value` keys and support updates via `patchState`.
+ * Each named resource is also exposed directly on the store. Writable
+ * resources are exposed without `set` and `update`; other custom resource
+ * members, including `reload`, are preserved.
*
* Plain `Resource` values are exposed as read-only signals with `Value`
* but are not stored in state.
@@ -464,12 +475,27 @@ function createNamedResource(
const keys = Object.keys(dictionary);
const state: Record> = {};
- const props: Record> = {};
+ const props: Record = {};
const methods: Record boolean> = {};
for (const resourceName of keys) {
const res = dictionary[resourceName];
+ if (isResourceRef(res)) {
+ const value = valueSignalForErrorHandling(
+ res,
+ errorHandling,
+ ) as WritableSignal;
+ const { set: _set, update: _update, ...resourceProps } = res;
+ props[resourceName] = {
+ ...resourceProps,
+ value: computed(() => value()),
+ } satisfies NamedResourceProp;
+ state[`${resourceName}Value`] = value;
+ } else {
+ props[resourceName] = res;
+ }
+
props[`${resourceName}Status`] = res.status;
props[`${resourceName}Error`] = res.error;
props[`${resourceName}IsLoading`] = res.isLoading;
@@ -480,10 +506,6 @@ function createNamedResource(
: () => res.hasValue();
if (isResourceRef(res)) {
- state[`${resourceName}Value`] = valueSignalForErrorHandling(
- res,
- errorHandling,
- ) as WritableSignal;
methods[`_${resourceName}Reload`] = () => res.reload();
} else {
props[`${resourceName}Value`] = valueSignalForErrorHandling(
@@ -562,7 +584,7 @@ function isResourceCoreKey(key: string): key is ResourceCoreKeys {
}
function assignPrefixedProps(
- target: Record>,
+ target: Record,
resourceName: string,
source: Record>,
): void {
From eca80cbd13f655f22ea8e82bd09d253d54d25ab0 Mon Sep 17 00:00:00 2001
From: Michael Small
Date: Sun, 25 Oct 2026 13:35:17 -0500
Subject: [PATCH 3/3] chore: add examples of proposal of resource as prop
---
.../with-resource/with-resource.component.ts | 103 +++++++++++++++++-
libs/ngrx-toolkit/src/lib/with-resource.ts | 6 +
2 files changed, 103 insertions(+), 6 deletions(-)
diff --git a/apps/demo/src/app/with-resource/with-resource.component.ts b/apps/demo/src/app/with-resource/with-resource.component.ts
index 761f4287..58f49d89 100644
--- a/apps/demo/src/app/with-resource/with-resource.component.ts
+++ b/apps/demo/src/app/with-resource/with-resource.component.ts
@@ -1,6 +1,13 @@
import { JsonPipe } from '@angular/common';
-import { httpResource } from '@angular/common/http';
-import { Component, inject } from '@angular/core';
+import { httpResource, HttpResourceRef } from '@angular/common/http';
+import {
+ Component,
+ effect,
+ inject,
+ Resource,
+ ResourceStatus,
+ Signal,
+} from '@angular/core';
import { withResource } from '@ngrx-toolkit/core';
import { signalStore, withState } from '@ngrx/signals';
import { Flight } from '../shared/flight';
@@ -12,11 +19,14 @@ export const FlightStore = signalStore(
withResource(({ flightTo }) =>
httpResource(() => `${url}${flightTo()}`),
),
- withResource(({ flightTo }) => ({
- list: httpResource(() => `${url}${flightTo()}`, {
- defaultValue: [],
+ withResource(
+ ({ flightTo }) => ({
+ list: httpResource(() => `${url}${flightTo()}`, {
+ defaultValue: [],
+ }),
}),
- })),
+ { errorHandling: 'native' },
+ ),
);
@Component({
@@ -27,4 +37,85 @@ export const FlightStore = signalStore(
})
export class WithResourceComponent {
store = inject(FlightStore);
+
+ constructor() {
+ effect(() => {
+ // Four things
+ // 1 - The largest benefit/requirement: declarative, simple to understand resource prop that can only patch the value state (can still reload if present)
+ // 2 - Modest enhancement followup: type a bit less verbose than at this current point
+ // 3 - PROPOSAL - stable NgRx `withResource` does not retain derived state other than the value
+ // 4 - PROPOSAL - drop errorHandling from stable NgRx `withResource` in favor of `extendResource`
+ //
+ // (1) What is possible / practical now - direct resource prop that must patch value (can still reload if present)
+ // Can jump directly to the resource :) since there is more than the derived values. This is HUGE.
+ // In this current moment, we still preserve the derived values. IMO for the Toolkit,
+ // it makes sense to keep them. But for NgRx itself, IMO only keep derived, patchable value.
+ //
+ // Now in this branch we have a normal, familiar resource experience while the value patching
+ // is still only possible in the store from the derived value.
+ // Not only is only having access to every single derived piece of state a bit too abstract and not as intuitive,
+ // it is also frustrating to not be able to jump to the definition. I have heard this from
+ // teammates and other users. And people who are not used to resources have added friction,
+ // as the full experience of drilling into a resource and its type is lost with the derived values.
+ // When I instead did a step inbetween the current `withResource` and this branch, aka I made a following
+ // block with a `withProps` that did `return {listResource: mapToResource(store, 'list')`}`, my
+ // teammates found that so much more understandable and easier to get to the definition of the resource.
+ //
+ // Overall:
+ // (a) More declarative to go back to the definition
+ // (b) Less noise and indirection from derived values
+ // (c) Transferable to normal resource experience BUT
+ // (d) Still can only update the value w/the derived value by `patchState`
+ // (e) Reload is still exposed if it was apart of the existing resource
+ // (f) Outstanding question: what about unnamed resources?
+ const listResourceAccess: Omit<
+ HttpResourceRef,
+ 'value' | 'set' | 'update'
+ > &
+ Resource = this.store.list;
+ //
+ // Direct value access from resoruce prop
+ const value: Signal = listResourceAccess.value;
+ //
+ // The one derived type left
+ const valueDerived: Signal = this.store.listValue;
+ //
+ // (2) Proposal for less verbose type
+ // I imagine we could make a custom type to be less verbose...
+ // WithResource>?
+ // While the `Ref` of `HttpResoruceRef` may make `value/set/update` seem tangible
+ // to use, I think if we clearly explain that `WithResource` would stip those away from
+ // the access to the resource prop, then this would be as straight forward as possible IMO.
+ const listResourceType: Omit<
+ HttpResourceRef,
+ 'value' | 'set' | 'update'
+ > &
+ Resource = this.store.list;
+ //
+ // (3) PROPOSAL Drop all derived values other than the `namedValue()` for NgRx's stable implementation. Only left in for Toolkit legacy.
+ // The derived types add a ton of noise to the store's state, and creates a branch away from the better way to access values directly from
+ // the resource that is derived as a prop. Deriving the `namedValue()` still makes sense as it is a special patchable state for the store.
+ // This also would save maintaining complexity.
+ const listResourceDerived = this.store.list;
+ //
+ // PROPOSED - Goes away for stable NgRx `withResource`, left for Toolkit legacy
+ // @ts-\expect-\error Would not work
+ const listResourceDerivedStatusDerivedStatus: Signal =
+ this.store.listStatus;
+ // Kept :) for stable NgRx `withResource`
+ const listResourceDerivedStatusPropsStatus: Signal =
+ listResourceDerived.status;
+ //
+ // Applies to all other derived values except the value.
+ // ??? Maybe go as far as make the derived value private to the store ???
+ //
+ // (4) PROPOSAL - drop error handling for the stable NgRx `withResource` in favor of `extendResource`
+ // `extendResource` is great and handles the error behavior well, for all resources or on case by case basis.
+ // The Toolkit error handling is fine to keep it for legacy reasons.
+ // But the typing gets much harder and unintuitive with the error handling and extended resources.
+ // Toolkit users with extended resources would have to opt into native error handling, but I say for stable it is
+ // just dropped and if a user wants it they use extended resource wrapper.
+ // This also would save maintaining complexity.
+ });
+ }
}
diff --git a/libs/ngrx-toolkit/src/lib/with-resource.ts b/libs/ngrx-toolkit/src/lib/with-resource.ts
index 94f06afd..721aae21 100644
--- a/libs/ngrx-toolkit/src/lib/with-resource.ts
+++ b/libs/ngrx-toolkit/src/lib/with-resource.ts
@@ -243,6 +243,9 @@ export type NamedResourceResult<
};
};
+// TODO - Get approval of this
+// My proposal is that for the Toolkit, we encourage native + `extendResource` error handling.
+// And for NgRx, drop error handling and leave it to the user to handle it with `extendResource`
export type ErrorHandling = 'native' | 'undefined value' | 'previous value';
export type ResourceOptions = {
@@ -687,6 +690,9 @@ export function mapToResource<
} as MappedResource;
}
+// TODO - Get approval of this
+// My proposal is that for the Toolkit, we encourage native + `extendResource` error handling.
+// And for NgRx, drop error handling and leave it to the user to handle it with `extendResource`
/**
* Strategies to work around the error throwing behavior of the Resource API.
*