NGRX 8减速器返回对象而不是数组

时间:2019-12-13 10:11:18

标签: angular typescript ngrx angular8 state-management

reducer返回的数据是一个对象,但我需要将其作为Array。 我已经尝试过返回action.recentSearches,但它似乎不起作用。

返回的数据是:

{ "loading": false, "recentSearches": [ { "corpId": "123", "site": "location", "building": "location", "floor": "2N" }, { "corpId": "123", "site": "location", "building": "location", "floor": "09" }, { "corpId": "123", "site": "location", "building": "location", "floor": "01" } ] }`

操作:

  export const getRecentSearches = createAction(
'[ConfRoom API] Request Recent Searches'
);

export const getRecentSearchesloadSuccess = createAction('[ConfRoom API] Recent Searches Load Success', props<{recentSearches: RecentSearchesModel[]}>());

诱人之处: console.log确实打印了我需要的值,但是返回action.recentSearches不起作用

export const initialState = [];
const _confRoomReducer = createReducer(
initialState,
on(confRoomActionTypes.getRecentSearches,  state=> ({      
  ...state
})),
on(confRoomActionTypes.getRecentSearchesloadSuccess,(state, { recentSearches }) => ({ ...state, recentSearches })) )

  export function confRoomReducer(state, action) {
  console.log(action.recentSearches);
return _confRoomReducer(state, action); 

组件中的值

recentSearches$: Observable<RecentSearchesModel[]> = this.store.select(state => state.recentSearches); 

更新

对reducer进行了2次编辑:

export const state = [];
export const initialState = [];


const _confRoomReducer = createReducer(
initialState,
on(confRoomActionTypes.getRecentSearches,  state=>     
 state
),
on(confRoomActionTypes.getRecentSearchesloadSuccess,(state,  {recentSearches} ) => ([ ...state, recentSearches ])) )

 export function confRoomReducer(state, action) {
return _confRoomReducer(state, action); 

现在像这样返回数据,但是我需要摆脱外部[],我用[]包装数据响应,在reducer中有一点,但这是我最接近的功能正确地:

    [ [ { "corpId": "123", "site": "location", "building": "location, "floor": "01,02" }, { "corpId": "123", "site": "location", "building": "location", "floor": "01,02" } ] ]

我的ngFor可以读取数据,但是它不能按预期工作,因为它要求我添加要显示的数据的索引:

 <tr *ngFor="let recentSearch of recentSearches$ | async; let i = index" ng-class-odd="'striped'">
  <td>{{recentSearch[0]}}, {{recentSearch[0].building}}, {{recentSearch[0].floor}}</td>
</tr>

更新 通过将建议的更改添加到化简器中,我能够提出解决方案,但是我不确定这是访问所需数据的正确方法

减速器

export interface RecentSearchesModel {
site: string;
corpId: string;
building: string;
floor: string
}

export interface State {
  resultList: RecentSearchesModel[];
}

const initialState: State = {
resultList: []
};


const _confRoomReducer = createReducer(
initialState,
on(confRoomActionTypes.getRecentSearches, state => ({
...state
})),
on(
confRoomActionTypes.getRecentSearchesloadSuccess,
(state, { recentSearches }) => ({ ...state, resultList: recentSearches })
  )
);

export function confRoomReducer(state, action) {
  return _confRoomReducer(state, action);
}

数据 现在像这样返回数据

{ "resultList": [ { "corpId": "123", "site": "CHINA", "building": "BUILDING 12", "floor": "2N" }, { "corpId": "123", "site": "US", "building": "BIG BUILDING", "floor": "09" }, { "corpId": "123", "site": "LONDON", "building": "BIG BEN", "floor": "01" } ] }

但是要访问我想要的组件数据,我必须编辑模型并添加resultList []

export interface RecentSearchesModel {
  corpId: string;
  site: string;
  building: string;
  floor: string;
resultList[];
}

我觉得我不必添加resultList到我的模型中,因为数据从未真正映射到它,我只是用它来访问数据所关联的标签 组件

recentSearches$: Observable<RecentSearchesModel[]> = this.store.select(state => state.recentSearches.resultList); 

2 个答案:

答案 0 :(得分:1)

您应该看看ngrx团队提供的example app

如果您要存储前端提供的数据,则表示初始化错误

您应该有一个供会议清单使用的界面

// have a model file:
export interface ConfRoom{
    corpId: number;
    site: string;
    location: string;
    floor: string;
}

// in your reducer
export interface State {
  confList: ConfRoom[];
}
const initialState: State = {
  confList: []
};


const _confRoomReducer = createReducer(
initialState,
// this line does nothing and can be delete...
// on(confRoomActionTypes.getRecentSearches,  state=>     
//  state
// ),
// if recentSearches should change confList do this
on(confRoomActionTypes.getRecentSearchesloadSuccess,(state,  {recentSearches} ) => ( {...state, confList: recentSearches})) )

// if recentSearches should be added to confList do this
on(confRoomActionTypes.getRecentSearchesloadSuccess,(state,  {recentSearches} ) => ( {...state, confList: [...confList, recentSearches]})) )

如果您要获取后端数据: 这是使用api调用并填充数据的示例。

这是一个仅带有负载的简单减速器:

import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';

import {
  ProjectCollectionApiActions,
  ProjectCollectionActions
} from '../../actions';
import { Project } from 'src/app/core/models';

export interface State extends EntityState<Project> {
  loading: boolean;
  loaded: boolean;
}

export const adapter: EntityAdapter<Project> = createEntityAdapter<Project>({
  selectId: (project: Project) => project.id,
  sortComparer: false,

});

export const initialState: State = adapter.getInitialState({
  loading: false,
  loaded: false
});

export const reducer = createReducer(
  initialState,
  on(ProjectCollectionActions.loadProjectCollection, (state) => ({
    ...state,
    loading: true,
  })),
  on(ProjectCollectionApiActions.loadProjectsSuccess,
    (state, { projects }) => adapter.addMany(projects, {
      ...state,
      loading: false,
      loaded: true
    })
  ),
);

export const getLoaded = (state: State) => state.loaded;

export const getLoading = (state: State) => state.loading;

我将其导入到名为index.ts的主文件中


import {
  createSelector,
  createFeatureSelector,
  combineReducers,
  Action,
} from '@ngrx/store';

import * as fromDates from './reports/dates.reducer';
import * as fromSuperIntendents from './superintendents/superintendent.reducer';
import * as fromReports from './reports/reports.reducer';
import * as fromProjects from './projects/projects.reducer';
import * as fromMachines from './machines/machines.reducer';

import * as fromLaborers from './laborers/laborers.reducer';
import * as fromCollection from './reports/collection.reducer';
import * as fromRoot from '../../../state/reducers';
import { generateMockReport, Report } from 'src/app/reports/models';

export interface DataState {
  dates: fromDates.State;
  superintendents: fromSuperIntendents.State;
  reports: fromReports.State;
  laborers: fromLaborers.State;
  collection: fromCollection.State;
  projects: fromProjects.State;
  machines: fromMachines.State;
}

export interface State extends fromRoot.State {
  data: DataState;
}

export function reducers(state: DataState | undefined, action: Action) {
  return combineReducers({
    dates: fromDates.reducer,
    superintendents: fromSuperIntendents.reducer,
    reports: fromReports.reducer,
    laborers: fromLaborers.reducer,
    collection: fromCollection.reducer,
    projects: fromProjects.reducer,
    machines: fromMachines.reducer
  })(state, action);
}



export const getDataState = createFeatureSelector<State, DataState>('data');

//here all my other reducers come
//...
//

export const getProjectsState = createSelector(
  getDataState,
  (state: DataState) => state.projects
);
export const {
  selectIds: getProjectIds,
  selectEntities: getProjectEntities,
  selectAll: getAllProjects,
  selectTotal: getTotalProjects,
} = fromProjects.adapter.getSelectors(getProjectsState); 

export const getProjectsLoaded = createSelector(
  getProjectsState,
  fromProjects.getLoaded
);

export const getLoadedProjectIds = createSelector(
  getProjectIds,
  (ids) => { return ids as string[] }
)

export const getLoadedProjects = createSelector(
  getProjectEntities,
  getLoadedProjectIds,
  (entities, ids) => {
      return ids
          .map(id => entities[id])
  }
);

这给了我这样的结果: enter image description here

参考效果页面:

import { Injectable } from '@angular/core';

import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';

import {
  ProjectCollectionApiActions,
  ProjectCollectionActions
} from '../../actions';

import { Project } from 'src/app/core/models';
import { LoggingService } from 'src/app/core/services/logging.service';
import { Update } from '@ngrx/entity';
import { ProjectService } from 'src/app/core/services/project.service';

@Injectable()
export class ProjectCollectionEffects {

  loadProjectCollection$ = createEffect(() =>
    this.actions$.pipe(
      ofType(ProjectCollectionActions.loadProjectCollection),
      switchMap(() => {
        return this.projectService.getList().pipe(
          map((projects: Project[]) =>
          ProjectCollectionApiActions.loadProjectsSuccess({ projects })
          ),
          catchError(error => {
            this.logging.log('Error in loadCollection effect"',"Project load collection effect - within Approvals")
            return of(ProjectCollectionApiActions.loadProjectsFailure({ error: {...error} }))
          })
        )
      })
    )
  );  


  constructor(
    private actions$: Actions,
    private projectService: ProjectService,
    private logging: LoggingService
  ) {}
}

编辑 如果您没有ID,则可以通过在服务中的数据中添加一个来伪造一个ID:

let counter = 0; 
return this.http.get<ConfRoom[]>(${url},httpOptions).pipe( 
    map((data: any) => { 
        let result: confRoom[] = []; 
        if(Array.isArray(data)){ 
            data.forEach(room=> { 
               result.push({...room, id: counter}); 
               counter = counter +1; 
            }); 
        } 
        return result; 
    }),
   catchError(handleError)
)

虽然听起来您只需要像我展示的第一部分那样的东西,但是我提到您在初始化错误? (第一段代码)

答案 1 :(得分:0)

您将作为对象返回,但其初始状态为[] 如下更改

 on(confRoomActionTypes.getRecentSearches,  state=> state)