簡體   English   中英

使用 StoreModule.forRoot 中的鍵並將選擇器范圍保持為僅狀態

[英]Using keys in StoreModule.forRoot and keeping the selector scoped to only state

我正在使用屬性鍵 'auth' 來限定 StoreModule.forRoot 設置中的減速器,以便將來可以添加其他減速器。

但這似乎與我的選擇器沖突。

./app.module.ts

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    StoreModule.forRoot({
      // here is a 'auth' key 
      auth: authStateReducer,
    }),
    EffectsModule.forRoot([AuthEffects]),
    //...

./auth.state.ts

export interface AuthState {
  token: string;
}

./auth.selectors.ts

export const selectToken = (state: AuthState) => state.token;

./auth.guard.ts

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private store: Store<AuthState>,
  ) {}

  this.store.select(selectToken)
      .subscribe((token) => {
        console.log(token) // logs undefined
      });
}

當我將商店調整為private store: Store<{ auth: AuthState }>, ,然后選擇器為: export const selectToken = ({ auth: state }) => state.token; 它確實有效。

但是,我的選擇器知道 app.module.ts 中的某些設置似乎很奇怪。

還有其他方法嗎?

首先選擇auth ,然后您可以從auth切片中選擇狀態。 要選擇頂級狀態,請使用createFeatureSelector

const selectAuthState = createFeatureSelector<AuthState>('auth');
export const selectToken = createSelector(selectAuthState, (state) => state.token);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM