From f49ee51fb72d9938f50fbaed8c2ba0d11f256378 Mon Sep 17 00:00:00 2001 From: Francesco Girelli Date: Tue, 11 Feb 2025 11:49:52 +0100 Subject: [PATCH] Update with-storage-sync.md storage factory explanation I added an example that explains how you can use the storage factory to inject a service to be used as a different storage system rather than the LocalStorage or SessionStorage. The use case was that i wanted to sync the state in a way that was not reachable and updateable by the user so i created a Storage implementation which holds everything in memory, every time you destroy a component in which the state is provided and you recreate it, the state is synced with that in memory Storage and the user will not be able to read it or change it. --- docs/docs/with-storage-sync.md | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/docs/with-storage-sync.md b/docs/docs/with-storage-sync.md index c6b6f59..6ae7c2f 100644 --- a/docs/docs/with-storage-sync.md +++ b/docs/docs/with-storage-sync.md @@ -41,3 +41,39 @@ public class SyncedStoreComponent { } } ``` +## Injecting services +The `storage` property requires a factory function that returns a `Storage` implementation. If you have a custom `Storage` implementation that is `Injectable`, you can provide it as a factory parameters using the `inject` function. + + Example: + + ```typescript +@Injectable({providedIn: 'root'}) +export class MyStorage implements Storage { + [name: string]: any; + length: number; + clear(): void { + ... + } + getItem(key: string): string | null { + ... + } + key(index: number): string | null { + ... + } + removeItem(key: string): void { + ... + } + setItem(key: string, value: string): void { + ... + } + +} + ``` + + ```typescript +const SyncStore = signalStore( + withStorageSync({ + storage: (myStorageImplementation = inject(MyStorage)) => myStorageImplementation, + }) +); +```