我正在尝试从数据库中获取用户信息。在组件中,我从服务中获取解码的 id,然后调用将 id 作为参数的操作。它返回用户,网络选项卡中有响应。状态属性"currentUser"始终为空,直到它应该更改为响应,然后它消失了。
export interface State {
loading: boolean;
loggedIn: boolean;
currentUser: User;
}
const initialState: State = {
loading: false,
currentUser: null,
loggedIn: localStorage.getItem("token") ? true : false
};
case AuthActions.GET_USER_SUCCESS:
{
return {
...state,
loading: false,
loggedIn: true,
currentUser: action.user
};
}
@Effect()
getUserInfo$: Observable < Action > = this.actions$
.ofType(fromActions.GET_USER)
.pipe(map((action: fromActions.GetUser) => action.id),
concatMap(id => {
return this.authService.getUser(id);
})
)
.pipe(map((res: User) => ({
type: fromActions.GET_USER_SUCCESS,
payload: res
})));
}
像这样尝试:
@Effect()
getUserInfo$: Observable<Action> = this.actions$
.ofType(fromActions.GET_USER)
.pipe(
map((action: fromActions.GetUser) => action.id),
concatMap(id =>
this.authService.getUser(id).pipe(
map((res: User) => ({
type: fromActions.GET_USER_SUCCESS,
payload: res
}))
)
)
);
你的动作类的形状是什么?我可以看到你以以下形式调度一个动作
{
type: fromActions.GET_USER_SUCCESS,
payload: res
}
但是在您的减速器中,您希望它具有user
属性
case AuthActions.GET_USER_SUCCESS:
{
return {
...state,
loading: false,
loggedIn: true,
currentUser: action.user // <- try action.payload or action.payload.user,
// depending on what you get from the API
};
}
另外,尝试像这样塑造您的效果:
@Effect()
getUserInfo$: Observable <Action> = this.actions$
.ofType(fromActions.GET_USER)
.pipe(
switchMap(({ id }) => this.authService.getUser(id)
.pipe(
map((res: User) => ({ type: fromActions.GET_USER_SUCCESS, payload: res }),
// Handling errors in an inner Observable will not terminate your Effect observable
// when there actually is an error
catchError(err => ({ type: fromActions.GET_USER_ERROR, payload: err })
)
)
);
希望这对:)有所帮助