我使用@ngxs/storage-plugin
将应用程序状态同步到本地存储中。序列化状态的默认存储密钥是@@STATE
,有没有办法重命名默认密钥?
我注意到在调用NgxsStoragePluginModule.forRoot
时,我可以使用key
选项来更改状态切片的存储密钥,但是当我尝试存储整个状态时它不起作用
key
选项应该被命名为path
。它不引用本地存储中使用的密钥的名称。尽管@@STATE
还在同名的本地存储中创建了一个密钥。
key
选项是状态存储中的一个或多个点表示法。例如;
interface MyModel { example: string }
@State<MyModel>({
name: 'app',
defaults: { example: "Hello World" }
) //...
如果密钥设置为@@STATE
则存储将保存
"@@STATE" : "{app: {example: 'Hello World'}}"
当您更改键时,它必须指向状态对象,否则它将产生undefined
。因此,我们可以将key
设置为"example"
,这将"Hello World"
存储在名为"example"的键下的 localStorage 中。
喜欢这个
"example": "Hello World"
截至目前,值@@STATE
在插件中是硬编码的,无法重命名。它对整个商店进行序列化具有特殊意义。否则,键必须是状态对象的点路径。
虽然您无法覆盖"@@state"常量,但您可以做的是修改用于保存状态的工程。在为操作存储而构建的服务中,可以输入所需的密钥。
您的模块
@NgModule({
imports: [
NgxsModule.forRoot([AuthState], {
developmentMode: !environment.production,
}),
NgxsReduxDevtoolsPluginModule.forRoot({ disabled: environment.production }),
NgxsStoragePluginModule.forRoot({ storage: StorageOption.SessionStorage }),
],
providers: [
{
provide: STORAGE_ENGINE,
useClass: MyStorageEngine,
},
],
})
export class YourModule {}
并在您的服务类中
@Injectable()
export class MyStorageEngine implements StorageEngine {
readonly yourKey = '@@YOUR_KEY';
constructor(private storageService: YourStorageService) {}
get length(): number {
return this.storageService.length;
}
getItem(key: string): any {
return this.storageService.getItem(this.yourKey);
}
setItem(key: string, value: any): void {
this.storageService.setItem(this.yourKey, value);
}
removeItem(key: string): void {
this.storageService.removeItem(this.yourKey);
}
clear(): void {
this.storageService.clear();
}
}