如何更改 Spartacus 默认的 token 存储方式

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,重载标准的 AuthStatePersistenceServiceinitSync 方法:

@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
  }
]

猜你喜欢

转载自blog.csdn.net/i042416/article/details/124415565