【发布时间】:2017-04-20 03:48:08
【问题描述】:
我的应用程序使用 ngrx/rxjs。我依靠 ngrx 效果从商店中注销和清除状态。
不幸的是,因为我的一个组件通过选择器订阅了商店(见下文:getLatestMessagesByCounterParty),并且因为在该组件被销毁之前清除了状态,所以我收到以下错误:
错误类型错误:无法读取 null 的属性“id” 在 getCurrentUserAccountId 处
...表示currentUserAccount是null,这很符合逻辑,因为我刚刚从商店中清除了状态。
这里是signout$ 效果:
@Effect()
signout$: Observable<Action> = this.actions$
.ofType(authenticated.ActionTypes.SIGNOUT)
.switchMap(() =>
this.sessionSignoutService.signout()
.do(() => {
localStorage.removeItem('authenticated');
localStorage.removeItem('sessionToken');
})
.concatMap(() => [
new ClearMessagesAction(null),
new ClearUserAccountAction(null),//Error thrown here...
go(['/signin'])//Never reached...
]));
这里是订阅登录状态的组件:
ngOnInit() {
this.store.select(fromRoot.getLatestMessagesByCounterParty)
.subscribe(latestMessages => this.latestMessages = this.messageService.sortMessagesByDate(latestMessages, this.numberOfConversations));
}
以及相关的选择器:
...
const getCurrentUserAccountId = (state: State) => state.userAccount.currentUserAccount.id;
const getMessagesState = (state: State) => state.message.messages;
...
export const getLatestMessagesByCounterParty = createSelector(getCurrentUserAccountId, getMessagesState, fromMessage.latestMessagesByCounterParty);
我正在寻找关于何时、何地以及如何从商店中清除状态的最佳做法。理想情况下,我希望在订阅组件被销毁的最后时间这样做。
有人可以建议吗?
编辑:让我进一步完善我的评论。我上面的代码应该如下所示。
.concatMap(() => [
new ClearMessagesAction(null),
new ClearUserAccountAction(null),//Error thrown right after this action because selector cannot find id variable on state
go(['/signin'])//Never reached...
]));
【问题讨论】:
-
听起来你需要在某处添加
filter(account => !!acount) -
你好 Cgatian。感谢您的回复。我想知道是否没有比添加过滤器更好的做法......
-
你好 Cgatian:你能提供一个关于如何在选择器上添加过滤器的例子吗?
标签: ngrx reselect ngrx-effects