1、在actions文件夹下创建action文件appName.action.ts
import { Action } from "@ngrx/store";
export const types = {
UPDATE_APPNAME: "UPDATE_APPNAME"
}
export class UpdateAppNameAction implements Action {
readonly type = types.UPDATE_APPNAME;
constructor(public payload:string){}
}
export type Actions = UpdateAppNameAction
|
2、在store文件夹下创建reducer文件appName.reducer.ts
import * as UpdateAppNameAction from "../actions/appName.action";
// 定义 reducer的State
export interface AppNameState {};
// State的初始默认值
const initialState: AppNameState = {
appname: "test"
};
// 定义action 如何改变state的状态
export function appNameReducer(state:AppNameState = initialState,action:UpdateAppNameAction.Actions){
switch(action.type){
case UpdateAppNameAction.types.UPDATE_APPNAME:
return Object.assign({}, state, {
appname: action.payload
});
default:
return state;
}
}
|
3、在app.module.ts中引入
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
StoreModule.forRoot({ appNameStateSelect: appNameReducer })
]
})
|
4、在app.component.ts中获取,并通过action更新store中的appName
// 获取到appName作为全局变量使用
setTimeout(()=>{
this.store.dispatch({// 通知action,通过action更新store
type: types.UPDATE_APPNAME,
payload: new Date()
})
},1000)// 此处在实际项目中改为从后端获取
|
5、在模块中调用
AppNameState$: Observable<AppNameState>;
constructor(private store: Store<AppNameState>) {
this.AppNameState$ = store.select("appNameStateSelect");//// 从app.module.ts中获取appidStateSelect状态流
}
ngOnInit() {
this.AppNameState$.subscribe((state: any) =>{
console.log(state) // 查看输出信息即为全局变量APPName
console.log(state.appname);
})
}
|
参考:https://blog.csdn.net/gaiery/article/details/103312248(主要参考,根据此链接实际操作一遍)