在Angular 9中,要注册一个全局的reducer,你需要创建一个Root Reducer,然后将它注册到NGRX的store中。下面是一个解决方法的示例代码:
首先,创建一个reducers文件夹,并在其中创建一个index.ts文件。
在index.ts文件中,引入NGRX的ActionReducerMap和你要注册的reducer。
import { ActionReducerMap } from '@ngrx/store';
import { reducer as globalReducer } from './global.reducer';
export interface AppState {
// 定义你的应用程序状态
}
export const reducers: ActionReducerMap = {
global: globalReducer,
// 添加其他reducer
};
global.reducer.ts文件中,编写你的全局reducer。import { Action } from '@ngrx/store';
export interface GlobalState {
// 定义你的全局状态
}
export const initialState: GlobalState = {
// 定义初始状态
};
export function reducer(state = initialState, action: Action): GlobalState {
switch (action.type) {
// 处理你的action
default:
return state;
}
}
app.module.ts文件中,将reducers注册到NGRX的store中。import { StoreModule } from '@ngrx/store';
import { reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers),
// 其他模块
],
// 其他配置
})
export class AppModule { }
现在,你已经成功注册了一个全局的reducer。你可以在应用程序的任何组件中使用它,通过使用@ngrx/store中的select操作符来选择和订阅全局状态。
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { GlobalState } from './reducers/global.reducer';
@Component({
selector: 'app-root',
template: `
{{ globalState | async | json }}
`
})
export class AppComponent {
globalState: Observable;
constructor(private store: Store<{ global: GlobalState }>) {
this.globalState = this.store.select('global');
}
}
这是一个基本的示例,你可以根据你的需求进行扩展和定制。希望对你有所帮助!