从 LocalStorage 补水状态的正确 RxJS/NgRx 方式是什么?
假设应用程序需要通过从 LocalStorage 读取 AuthToken 来了解用户是否已登录。这应该是 NgRx Store 初始化后的第一件事。
对于这种情况,AuthStore 有一个操作 initAuth
其关联的 Effect 在服务的帮助下填充状态,同时从 LocalStorage 读取 token 。
目前我正在调度initAuth
里面 ngOnInit
应用组件:
@Component({
selector: 'app-root',
...
})
export class AppComponent implements OnInit {
constructor(protected readonly store$: Store<State>) {
}
ngOnInit(): void {
this.store$.dispatch(authActions.initAuth());
}
}
但感觉应该有更好的办法。
我正在考虑将效果与以下
@ngrx/effects/init
相关联 dispatch 行动initAuth
(如果可能,如何实现?):备注 : 我没有使用 ngrx-store-localstorage .
最佳答案
您可以使用 ROOT_EFFECTS_INIT
Action 并在效果中做任何你想做的事情。
import { ofType, Actions, Effect, ROOT_EFFECTS_INIT } from '@ngrx/effects';
class InitEffects {
@Effect()
init$ = this.actions$
.ofType(ROOT_EFFECTS_INIT)
.pipe(tap(() => window.alert('I should be shown')));
constructor(private actions$: Actions) {}
}
还要确保在
forRoot
中注册此效果。方法,功能模块将不起作用。
关于angular - 使用 LocalStorage 中的 AuthToken 为 NgRx Store 补水的正确方法和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55164955/