该逻辑实现在文件auth.service.ts内:
isUserLoggedIn(): Observable<boolean> {return this.authStorageService.getToken().pipe(map((userToken) => Boolean(userToken?.access_token)),distinctUntilChanged());}
如果能从authStorage service里拿到token,且token结构的access_token字段不为空,则说明用户登录成功。
getToken的实现:auth-storage.service.ts
protected _token$: Observable<AuthToken> = new BehaviorSubject<AuthToken>({} as AuthToken);
BehaviorSubject就是一个广播机制。
_token$什么时候发生变化呢?得对其使用where Used List.
在Spartacus初始化的时候:
export function authStatePersistenceFactory(authStatePersistenceService: AuthStatePersistenceService) {const result = () => authStatePersistenceService.initSync();return result;}
SyncwithStorage:
这里就把local storage里存储的token取出来了:
具体读取逻辑写在state-persistence.service.ts的readFromStorage里:
标号为3处的代码一旦subscribe后,先触发1处的readFromStorage, 结果作为输入,传递给2处的tap Operator里的箭头函数:
onRead,将从浏览器local storage取出的token,设置到state里:
更多Jerry的原创文章,尽在:“汪子熙”: