0

我正在触发 的调度onInitshell component但将值设为undefined。如果我刷新页面,值会从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;
})

外壳组件:

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
  }

}
4

1 回答 1

1

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

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',
于 2021-09-19T17:29:49.110 回答