当要素切片为空时,NgRx选择器

时间:2018-01-22 09:11:58

标签: angular typescript ngrx ngrx-store-4.0

在我的应用程序中,有一个带有功能片的商店:

@NgModule({
    imports: [
    CommonModule,
    TranslateModule.forChild({}),
    StoreModule.forFeature('slice', slice)
    ...
})

功能的Reducer Map:

export const slice: ActionReducerMap<SliceState> = {
    someReducer
};

功能选择器:

export const selectSliceModule = createFeatureSelector<SliceState>('slice');
export const selectItem = createSelector(selectSliceModule,
(state: SliceState) => state.someReducer.paramA);

退出后会有一个退出操作,清除主要商店以及slice后退出slice === null

使用选择器selectItem订阅要素存储片的组件 然后失败,因为state.someReducer为空:state.someReducer.paramA

我的问题是:在这种情况下,在选择器中使用三元运算符是否可以?  它会破坏选择器的记忆吗?或者有更好的方法来处理这种情况吗?

// Is it OK to have ternary operator in selector?
export const selectItem = createSelector(selectSliceModule,
(state: SliceState) => state.someReducer ? state.someReducer.paramA : null);

2 个答案:

答案 0 :(得分:1)

我遇到了这个问题,然后意识到状态的受影响部分的化简在其switch语句中没有默认情况,该语句返回了传递给化简函数的状态。如果没有这种默认情况,则reducer返回的初始状态是不确定的。添加默认状态对我来说解决了这个问题。希望这对您也有帮助。

答案 1 :(得分:0)

我知道这个问题很旧,但这也许可以帮助某个人。

面对同样的问题,这是因为我的组件在销毁数据后尝试访问数据。

添加 takeUntil 解决了我的问题

this.restaurantData$ = this.restaurantQuery$
      .pipe(
        takeUntil(this._ngOnDestroy), // Added this line
        filter((restaurantQuery) => !!restaurantQuery),
        switchMap((restaurantQuery) => restaurantQuery.valueChanges),
        map((response) => response.data.vendor)
      ); 

现在注销后,组件停止监听选择器。

相关问题