Angular - Redux Thunk AppState не определено - PullRequest
0 голосов
/ 04 сентября 2018

Я не новичок в Redux Thunk, но теперь я думаю, что что-то пропустил, потому что он не работает правильно, и я просто не могу понять. Класс моих действий:

    @Injectable()
    export class UserBOActions {
service: WebApiPromiseService;

  constructor(private http: Http, @Inject(APP_STORE_TOKEN) private appStore, private httpClient: HttpClient) {
    this.service = new WebApiPromiseService(http, this.userToken.toString());
  }

  get userToken(): any[] {
    return this.appState.user.userToken;
  }

  get appState(): AppState {
    return this.appStore.getState();
  }
         GetTypes(Token: string) {
            return async (dispatch) => {
              const userTypes = await this.service.getService("User/GetUserTypes", Token);

              dispatch({
                type: "INIT_GetTypes",
                userTypes: userTypes
              });
            }
          }
          GetResources(Token: string) {
            return async (dispatch) => {
              const resources = await this.service.getService("User/GetDestinationResource", Token);

              dispatch({
                type: "INIT_GetResources",
                resources: resources
              });
            }
          }
    }

Класс редуктора:

import { LkpUserDestinationResource } from "../../Model/LkpUserDestinationResource";
import { LkpUserType } from "../../Model/LkpUserType";

export interface UserBOContentState {
  res: boolean;
  userTypes: LkpUserType[];
  resources: LkpUserDestinationResource[];
}

export function UserBOContentReducer(state: UserBOContentState, action) {

  if (state === undefined) {
    return {
    };
  }


  if (action.type == "INIT_UpdateUser") {
    return {
      res: action.res,
      userTypes: state.userTypes,
      resources: state.resources,
    };
  }

  if (action.type == "INIT_GetTypes") {
    return {
      res: state.res,
      userTypes: action.userTypes,
      resources: state.resources,
    };
  }

  if (action.type == "INIT_GetResources") {
    return {
      res: state.res,
      userTypes: state.userTypes,
      resources: action.resources,
    };
  }

  return state;
}

Класс App Store:

import { InjectionToken } from "@angular/core";
import reduxThunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { UserBOContentState, UserBOContentReducer } from './BackOffice/reducers/user.reducer';
export interface AppState {
  userBO: UserBOContentState;
}

const reducer = combineReducers({
  userbo: UserBOContentReducer
})
const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    state = undefined
  } return reducer(state, action)
}

export const appStore = createStore(rootReducer, composeWithDevTools(applyMiddleware(reduxThunk)));
export const APP_STORE_TOKEN = new InjectionToken("APP_STORE_TOKEN");

Класс модуля приложения:

import { UserBOActions } from "./BackOffice/actions/user.actions";
  providers: [
   UserBOActions
{ provide: APP_STORE_TOKEN, useValue: appStore },
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    OnlyLoggedInUsersGuard,
    CookieService,

  ]

Обратите внимание, что я разместил только соответствующие части App Store и App Module, это большой полностью рабочий проект, а в остальных местах, где я использую Redux, проблем нет.

Теперь я пытаюсь получить значения из UserBOActions следующим образом. ngOnInit ():

this.appStore.dispatch(this.userActions.GetResources(this.userToken.toString()));
    this.appStore.dispatch(this.userActions.GetTypes(this.userToken.toString()));
let interval = setInterval(() => {
        if (this.userTypes != null && this.resources != null) {
          clearInterval(interval);
          this.curType = this.userTypes.find(t => t.UserTypeID === this.user.UserTypeID);
          this.curResource = this.resources.find(t => t.UserDestinationResourceID === this.user.UserDestinationResourceID); 
        }
      }, 100);

Возвращает:

get userTypes(): LkpUserType[] {
    if (this.appState.userBO) {
      return this.appState.userBO.userTypes;
    }
  }


  get resources(): LkpUserDestinationResource[] {
    if (this.appState.userBO) {
      return this.appState.userBO.resources;
    }
  }

При отладке и печати на консоли я вижу, что "userBO" не определено. НО, просматривая Redux DevTools, я вижу, что он содержит все данные:

redux devtools

Есть идеи, что пошло не так?

Спасибо !!

1 Ответ

0 голосов
/ 04 сентября 2018

Заглавные буквы важны, userbo не userBO

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...