Spartacus 默认的存储方式是 localStorage
,我们可以采取二次开发的方式,将其替换成 SessionStorage
.
默认的实现:AuthStatePersistenceService
:
/**
* Initializes the synchronization between state and browser storage.
*/
public initSync() {
this.subscription.add(
this.statePersistenceService.syncWithStorage({
key: this.key,
state$: this.getAuthState(),
onRead: (state) => this.onRead(state),
})
);
}
新建一个 CustomAuthStatePersistenceService
,重载标准的 AuthStatePersistenceService
的 initSync
方法:
@Injectable({ providedIn: 'root' })
export class CustomAuthStatePersistenceService extends AuthStatePersistenceService {
initSync() {
this.subscription.add(
this.statePersistenceService.syncWithStorage({
key: this.key,
state$: this.getAuthState(),
onRead: (state) => this.onRead(state),
storageType: StorageSyncType.SESSION_STORAGE, // 此处传入自定义的 storage 类型
})
);
}
}
然后在 providers
区域进行替换:
providers: [
{
provide: AuthStatePersistenceService,
useExisting: CustomAuthStatePersistenceService
}
]