Before Spartacus version 2.0, the only way to achieve state persistence was to use a simple declarative mechanism called storageSync, which allowed you to provide attribute keys for persistence in storage. When you start your application, these persistent keys are used to set the initial state in storage. With Spartacus 2.0 or later, you can maintain the state of the storefront application by using StatePersistenceService, especially its syncWithStorage method. It is not as simple as storageSync, but it provides more control using context and a dedicated onRead callback.
You can pass the following options to the syncWithStorage function: key, state$, context$, storageType, and onRead.
These options work as follows:
(1) The key is used to distinguish one feature from another in the storage. For example, to store the active shopping cart id, you can use the shopping cart key, and for user session data, you can use the session key.
(2) state$ is an observable object, it will emit a value every time you want to save a new value to persistent storage. For example, to retain the active shopping cart id every time the active shopping cart id changes, this observable emits a new value.
(3) context$ is an observable, which describes the effective context of a specific state. For example, the active shopping cart ID is only valid for one base site. You want to use different shopping carts on different basic sites. In this case, using context$, you will use the observable that emits the base site every time it changes.
storageType specifies the storage type used. By default, the storage type is local storage, but you can change it to session storage, etc.
onRead is a callback that is called every time the context changes. Taking the shopping cart as an example, every time the base site is changed, the callback for that specific context is called with the value read from the storage. If nothing is saved in the storage, it will dispatch the undefined value.
At runtime, this logic is initialized by APP_INITIALIZER:
The returned result is a function:
toPromise will finally trigger subscribe:
More original articles by Jerry, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。