我希望当 API 调用返回用户时,状态会更新并且 home.component.html 显示新值。我也在使用 ngrx devtools,我可以看到状态变化,但 html 没有更新。这就是我拥有的。
home.component.ts
export class HomeComponent implements OnInit {
meUser$ = this.store.select(selectMeUser);
constructor(private store: Store<AppState>) { }
ngOnInit(): void {
this.store.dispatch(loadMeUser());
}
home.component.html
<p *ngIf="meUser$ | async as me">
Hi, {{ me.firstname }}
</p>
用户.actions.ts
export const loadMeUser = createAction('[User] Load Me User');
export const loadMeUserSuccess = createAction(
'[User] Load Me User Success',
props<{ user: User }>()
);
export const loadMeUserFailure = createAction(
'[User] Load Me User Failure',
props<{ error: string }>()
);
user.reducers.ts
export interface UserState {
meUser: User | null;
status: string;
error: string;
}
export const initialstate: UserState = {
meUser: null,
status: 'pending',
error: ''
}
export const userReducer = createReducer(
initialstate,
on(loadMeUser, (state) => ({ ...state, status: 'loading' as StatusType })),
on(loadMeUserSuccess, (state, { user }) => ({
...state,
meUser: user,
error: '',
status: 'success'
})),
on(loadMeUserFailure, (state, { error }) => ({
...state,
error: error,
status: 'error'
}))
)
用户.selectors.ts
export const selectUser = (state: AppState) => state.user;
export const selectMeUser = createSelector(
selectUser,
(state: UserState) => state?.meUser
)
用户.effects.ts
@Injectable()
export class UserEffects {
constructor(
private actions$: Actions,
private store: Store<AppState>,
private userService: UserService
) {}
loadMeUser$ = createEffect(() =>
this.actions$.pipe(
ofType(loadMeUser),
exhaustMap(() => {
return this.userService.getMeUser().pipe(
map((data) => {
return loadMeUserSuccess({ user: data });
}),
catchError((error) => of(loadMeUserFailure({ error: error })))
)
})
)
)
}
在开发工具中,我可以看到状态结果是成功,如果我在效果中添加console.log,则数据是正确的,如果我将其更改为
meUser$ = this.store.select(selectMeUser).subscribe((data) => console.log(data))
,我会得到未定义的信息。
我错过了什么?