Ngrx 存储 - 如何 select 根状态

Ngrx store - how to select root state

我正在从 appsettings.json 加载配置文件,其中我保存了 api url。

我已经设置了 ngrx 7 商店,有效果。我在 app.component.ts onInit 中调度 loadconfig 操作,然后我尝试从控制台中的存储中读取数据。我得到一个错误:

TypeError: Cannot read property 'getConfig' of undefined at new AppFacade (VM5613 main.js:2060)

我认为问题在于我如何为 root 实现选择器。如您所见,我使用了 createFeatureSelector,但根状态不是功能,而是根。我究竟做错了什么?为什么我无法访问状态值,因为它说它是未定义的,但在 redux 中 chrome devtools 状态显然存在?

状态存储如下所示:

这就是我实现商店的方式:
操作:

import { Action } from '@ngrx/store';
import { AppConfig } from '../../app.config';

export enum AppActionTypes {
  LoadConfig = '[App] Load Config',
  LoadConfigError = '[App] Load Config Error',
  LoadConfigSuccess = '[App] Load Config Success'
}

export class LoadConfig implements Action {
  public readonly type = AppActionTypes.LoadConfig;
}

export class LoadConfigError implements Action {
  public readonly type = AppActionTypes.LoadConfigError;
  constructor(public payload: any) {}
}

export class LoadConfigSuccess implements Action {
  public readonly type = AppActionTypes.LoadConfigSuccess;
  constructor(public payload: AppConfig) {}
}

export type AppActions = LoadConfig | LoadConfigError | LoadConfigSuccess;

export const fromAppActions: any = {
  LoadConfig,
  LoadConfigError,
  LoadConfigSuccess
};

效果:

import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { AppActionTypes } from '../actions/app.actions';
import { HttpClient } from '@angular/common/http';
import { mergeMap, map, catchError } from 'rxjs/operators';
import { AppConfig } from '../../app.config';
import { of } from 'rxjs';

@Injectable()
export class AppEffects {
  constructor(private actions$: Actions, private httpClient: HttpClient) {}

  @Effect()
  private loadConfig$: any = this.actions$.pipe(
    ofType(AppActionTypes.LoadConfig),
    mergeMap(() =>
      this.httpClient.get('assets/appsettings.json').pipe(
        map((response: AppConfig) => ({
          type: AppActionTypes.LoadConfigSuccess,
          payload: response
        })),
        catchError(() => of({ type: AppActionTypes.LoadConfigError }))
      )
    )
  );
}

门面:

import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { AppState } from '../reducers/app.reducer';
import { appQuery } from '../selectors/app.selectors';
import { AppConfig } from '../../app.config';
import { LoadConfig } from '../actions/app.actions';

@Injectable({
  providedIn: 'root'
})
export class AppFacade {
  constructor(private store: Store<AppState>) {}

  public getConfig: Observable<AppConfig> = this.store.pipe(
    select(appQuery.getConfig)
  );

  public loadConfig(): void {
    this.store.dispatch(new LoadConfig());
  }
}

减速器:

import { AppActions, AppActionTypes } from '../actions/app.actions';
import { AppConfig } from '../../app.config';

export const APP_KEY: string = 'app_key';

export interface AppState {
  appConfig: AppConfig | undefined;
}

export const initialState: AppState = {
  appConfig: {
    AppSettings: {
      AppUrl: undefined,
      ApiUrl: undefined,
      AuthUrl: undefined
    },
    ApplicationInsights: {
      InstrumentationKey: undefined
    }
  }
};

export function reducer(
  state: AppState = initialState,
  action: AppActions
): AppState {
  switch (action.type) {
    case AppActionTypes.LoadConfigSuccess: {
      return {
        ...state,
        appConfig: action.payload
      };
    }
  }

  return state;
}

选择器:

import {
  createFeatureSelector,
  MemoizedSelector,
  createSelector
} from '@ngrx/store';
import { AppState, APP_KEY } from '../reducers/app.reducer';
import { AppConfig } from '../../app.config';

// Lookup the 'account bar' feature state managed by NgRx
const getAppState: MemoizedSelector<
  object,
  AppState
> = createFeatureSelector<AppState>(APP_KEY);

const getConfig: MemoizedSelector<object, AppConfig> = createSelector(
  getAppState,
  (state: AppState) => state.appConfig
);

export const appQuery = {
  getConfig
};

应用程序模块:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { CoreModule } from './core/core.module';

import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

import { AppComponent } from './app.component';
import { AppEffects } from './store/effects/app.effects';
import { reducers } from './store/reducers';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    CoreModule,
    StoreModule.forRoot(reducers),
    EffectsModule.forRoot([AppEffects]),
    StoreDevtoolsModule.instrument({
      maxAge: 100,
      logOnly: false
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

应用程序组件:

import { Component, OnInit } from '@angular/core';
import { AppFacade } from './store/facades/app,facade';
import { AppConfig } from './app.config';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private facade: AppFacade) {}

  public ngOnInit(): void {
    this.facade.loadConfig();

    this.facade.getConfig.subscribe((response: AppConfig) => {
      console.log(JSON.stringify(response, null, 4));
    });
  }
}

好的,我发现了一个问题。我不会删除我的问题,因为商店的结构是世界 class,并且可能会帮助其他人。

问题是 reducer 中的 APP_KEY 是 "app_key",而不是 "app",正如您从图片中看到的状态名称是 "app",因此正在访问非现有状态。