ngrx结合localstorage思路(下面是获取用户信息):
1.登陆的时候接口会返回用户资料,
2.initialState默认读取localStorage里面的用户信息
3.订阅state里面的loginInfo,store.pipe(select('loginInfo')),实时获取数据
4.更新数据:一旦调用了this.store.dispatch(getLoginInfo({...}))方法更改了数据,步骤3就可以订阅到,
5.为防止刷新页面后信息丢失,调用getLoginInfo()方法后,更新localstorage里面的信息,然后initialState会被获取最新的用户信息
login.component.ts (登陆事件,存储登陆数据)
login(){
this.loginService.login(params).subscribe(data =>{
localStorage.setItem('USERINFO',JSON.stringify(data.userinfo));
})
}
action.ts
import { createAction,props } from '@ngrx/store';
export const getLoginInfo = createAction(
'[getLoginInfo Page] getLoginInfo',
props<{payload:any}>()
);
reducer.ts
...
// 设置初始值
const userInfo = localStorage.getItem('USERINFO');
export const initialState: any = userInfo;
const _loginInfoReducer = createReducer(initialState,
on(getLoginInfo, (state, action) => { // getLoginInfo是action.ts中定义的方法
return ({
...state,
...action.payload
})
})
);
...
update.component.ts
update(){
const params = {
username:'貂蝉',
phone:'1511111111',
sex:'女',
...
}
// 更新用户信息
this.loginService.update(params).subscribe(data =>{
// 更新localStorage里面的信息
localStorage.setItem('USERINFO',JSON.stringify(data.userinfo));
// 更新store里面的信息
this.store.dispatch(getLoginInfo({
payload:{
...params
}
}));
})
}
大功告成!