Ngrx存储-如何选择根状态

时间:2019-02-17 00:53:18

标签: redux ngrx ngrx-store

我正在从保存我的api URL的appsettings.json加载配置文件。

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

  

TypeError:无法读取未定义的属性'getConfig'       在新的AppFacade上(VM5613 main.js:2060)

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

状态已存储,如下所示: enter image description here

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

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));
    });
  }
}

1 个答案:

答案 0 :(得分:0)

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

问题在于,reducer中的APP_KEY是“ app_key”,而不是“ app”,如从图片状态名称中看到的是“ app”,因此正在访问不存在的状态。