`selector` return 页面刷新时的值,`onInit` 值显示为未定义

`selector` return the value on page refresh, `onInit` value shows as undefined

我在 shell componentonInit 上触发调度,但得到的值为 undefined。如果我刷新页面,值 return 正确地来自 selector。不知道如何解决这个问题。也没有收到任何错误。users 部分操作正常。

这是动作:

import { createAction, props } from "@ngrx/store";
import { PropUsers, PropUser } from "./reducer";

export const userActions = {
    GET_USERS: '[users] Get Users',
    GET_USERS_SUCESS: '[users] Get Users Success',
    GET_USERS_FAILURE: '[users] Get Users Failure',

    GET_PROFILE: '[users] Get Users',
    GET_PROFILE_SUCESS: '[users] Get Users Success',
    GET_PROFLE_FAILURE: '[users] Get Users Failure',
}

export const actionGetUsers = createAction(userActions.GET_USERS);
export const actionGetUsersSuccess = createAction(userActions.GET_USERS_SUCESS, props<{ users: PropUsers[] }>());
export const actionGetUsersFailure = createAction(userActions.GET_USERS_FAILURE, props<{ error: string }>());

export const actionGetProfile = createAction(userActions.GET_PROFILE);
export const actionGetProfileSuccess = createAction(userActions.GET_PROFILE_SUCESS, props<{ user: PropUser }>());
export const actionGetProfileFailure = createAction(userActions.GET_PROFLE_FAILURE, props<{ error: string }>());

选择器:

import { createSelector, createFeatureSelector } from '@ngrx/store';
const usersSelector = createFeatureSelector<any>("store");

export const selectUsers = createSelector(usersSelector, (state) => {
    return state.reducerUser.users;
})
export const selectProfile = createSelector(usersSelector, (state) => {
    console.log('state', state.reducerUser.profile);
    return state.reducerUser.profile;
})

shell分量:

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { Store, select } from "@ngrx/store";
import { Observable } from 'rxjs';
import { map } from "rxjs/operators";
import { PropUser } from '../../store/reducer';
import { actionGetProfile } from './../../store/actions';
import { selectProfile } from "./../../store/selectors";

@Component({
  selector: 'app-shell-user-profile',
  templateUrl: './shell-user-profile.component.html',
  styleUrls: ['./shell-user-profile.component.scss']
})
export class ShellUserProfileComponent implements OnInit {

  @Output() userProfile$: Observable<PropUser> = new EventEmitter<PropUser>();
  @Output() standClass: string;

  constructor(private readonly store: Store) {
    this.standClass = '12th';
  }

  ngOnInit(): void {
    this.store.dispatch(actionGetProfile());
    this.store.select(selectProfile).subscribe(data => console.log('data', data)); //undefined until refresh the page
  }

}

您应该为您的操作使用不同的字符串值。

GET_USERS: '[users] Get Users',

相同
GET_PROFILE: '[users] Get Users',

因此,即使看起来您正在触发不同的操作(因为您使用了另一个符号),但实际上您触发的是获取用户的相同操作。

你的每一个动作都应该有不同的字符串值。试试这个:

GET_PROFILE: '[users] Get Profile',
GET_PROFILE_SUCESS: '[users] Get Profile Success',
GET_PROFLE_FAILURE: '[users] Get Profile Failure',