Angular 组件不反映 NGRX 存储状态
Angular component does not reflect NGRX store state
我正在玩弄 Angular 和 ngrx,并按照几个不同的教程开始了一些 ngrx-store。我正在使用 ngrx-10 和 angular-11。设置相当简单。
app/store/action.ts
export const toggleSideNav = createAction('[SideNav Component] Toggle', props<{showSideNav?: boolean}>());
app/store/reducer.ts
export interface AppState {
showSideNav: boolean
}
export const initialState: AppState = {
showSideNav: true
};
const _appReducer = createReducer(
initialState,
on(toggleSideNav, (state: AppState, {showSideNav}) => ({...state, showSideNav: showSideNav ?? !state.showSideNav }))
);
export function AppReducer(state: AppState = initialState, action: Action) {
return _appReducer(state, action);
}
app.module.ts
...
StoreModule.forRoot({appStore : AppReducer}, {})
...
/访问者(子模块)/components/home.component.ts
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
showSideNav$: Observable<boolean>;
constructor(private store: Store<AppState>) {
this.showSideNav$ = store.pipe(select(x => x.showSideNav))
}
ngOnInit(): void {
}
toggleSideNav(): void {
this.store.dispatch(toggleSideNav({}));
}
}
最后,
/访客/components/home.component.html
<div *ngIf="showSideNav$ | async">
it works
</div>
<button (click)="toggleSideNav()">
Toggle
</button>
我正在使用 ngrx-devtools,我可以看到“showSideNav”作品的切换。它在 true 和 false 之间摇摆不定,但文本从不显示。好像 showSideNav$ 总是未定义的。
您的选择器 returns undefined
。我猜你的选择器函数应该是这样的:
select(x => x.appStore.showSideNav)
我正在玩弄 Angular 和 ngrx,并按照几个不同的教程开始了一些 ngrx-store。我正在使用 ngrx-10 和 angular-11。设置相当简单。
app/store/action.ts
export const toggleSideNav = createAction('[SideNav Component] Toggle', props<{showSideNav?: boolean}>());
app/store/reducer.ts
export interface AppState {
showSideNav: boolean
}
export const initialState: AppState = {
showSideNav: true
};
const _appReducer = createReducer(
initialState,
on(toggleSideNav, (state: AppState, {showSideNav}) => ({...state, showSideNav: showSideNav ?? !state.showSideNav }))
);
export function AppReducer(state: AppState = initialState, action: Action) {
return _appReducer(state, action);
}
app.module.ts
...
StoreModule.forRoot({appStore : AppReducer}, {})
...
/访问者(子模块)/components/home.component.ts
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
showSideNav$: Observable<boolean>;
constructor(private store: Store<AppState>) {
this.showSideNav$ = store.pipe(select(x => x.showSideNav))
}
ngOnInit(): void {
}
toggleSideNav(): void {
this.store.dispatch(toggleSideNav({}));
}
}
最后, /访客/components/home.component.html
<div *ngIf="showSideNav$ | async">
it works
</div>
<button (click)="toggleSideNav()">
Toggle
</button>
我正在使用 ngrx-devtools,我可以看到“showSideNav”作品的切换。它在 true 和 false 之间摇摆不定,但文本从不显示。好像 showSideNav$ 总是未定义的。
您的选择器 returns undefined
。我猜你的选择器函数应该是这样的:
select(x => x.appStore.showSideNav)