我掌握了ngrx的窍门,我已经做好了。。。但我做了很长时间,与我在网上看到的每一个教程/演练相比,这都是错误的,我想看看我是否能让它达到正确的状态。
我的问题有两个方面:
- 如果我不给状态一个名称,它在浏览器中是未定义的。这样可以:
import { reducers } from './state/app.reducers';
@NgModule({
declarations: [
AppComponent,
],
imports: [
StoreModule.forRoot({ appState: reducers }),
!environment.production ? StoreDevtoolsModule.instrument() : [],
EffectsModule.forRoot([AppEffects]),
StoreRouterConnectingModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
但是StoreModule.forRoot(reducers)
和大多数示例一样,在运行时会导致未定义状态。
- 我相信这一点,因为如果这样,我就无法引用根的状态,必须将其拔出。例如,这样做可以:
export class MyComponent implements OnInit {
state$: Observable<AppState>;
userId$: Observable<string>;
constructor(
private store: Store<{appState: AppState}>
) {
this.state$ = store.select('appState');
}
ngOnInit(): void {
this.userId$ = this.state$.pipe(select(s => s.userId));
}
}
我不能像大多数示例所包括的那样直接选择状态,而且它根本无法像大多数示例显示的那样只注入private store Store<AppState>
。
如果有帮助的话,我在运行时的状态看起来是这样的:
{
appState: {
userId: 'd229b5ef-b7a8-2600-6eed-427ee7b10637',
userName: 'test',
}
}
供参考。。。
// app/state/app.state.ts
export interface AppState {
userId: string;
userName: string;
}
export const initialState: AppState = {
userId: null,
userName: null
}
// app/state/app.reducers.ts
import { initialState } from './app.state';
const reducer = createReducer(
initialState,
on(updateUser, (state, { userId, userName })=> (
{
...state,
userId: userId,
userName: userName
}))
);
export function reducers(state, action) {
return reducer(state, action);
}
// app/state/app.selectors.ts
import { AppState } from './app.state';
export const selectUserId = (state: AppState) => state.userId
所以我有点不知所措。我已经让它工作了,在那里我可以存储状态并在运行时获取它,但它不是惯用的,而且它似乎非常脆弱。
问题是,您将一个减速器导出为减速器,然后尝试使用它。您需要导出该减速器,并创建一个将用作StoreModule.forRoot()
中减速器的减速器阵列。代码示例:
// app/state/app.reducers.ts
import { initialState } from './app.state';
const reducer = createReducer(
initialState,
on(updateUser, (state, { userId, userName })=> (
{
...state,
userId: userId,
userName: userName
}))
);
export function reducer(state, action) { // changed from 'reducers' to reducer
return reducer(state, action);
}
创建一个名为index.ts
:的新文件
// app/state/index.ts
import * as fromApp from 'app/state/app.reducer.ts',
export const reducers = [
appState: fromApp.reducer
]
然后导入减速器:
import { reducers } from './state/index.ts';
@NgModule({
declarations: [
AppComponent,
],
imports: [
StoreModule.forRoot(reducers),
!environment.production ? StoreDevtoolsModule.instrument() : [],
EffectsModule.forRoot([AppEffects]),
StoreRouterConnectingModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }