gpt4 book ai didi

angular - NGRX 8 reducer 返回对象而不是数组

转载 作者:行者123 更新时间:2023-12-04 10:54:04 25 4
gpt4 key购买 nike

reducer 返回的数据是一个对象,但我需要它是一个数组。我试过返回 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[]}>());

redcuer: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>

更新通过将推荐的更改添加到 reducer 中,我能够提出解决方案,但我不确定它是否是访问我需要的数据的正确方法

reducer

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

最佳答案

你应该看看 example app由 ngrx 团队提供。

如果您尝试存储前端提供给您的数据,那么您的初始化是错误的

您应该有一个用于 session 室列表的界面

// 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 调用和填充数据时的示例。

这是一个只有负载的简单 reducer :

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,您可以通过向服务中的数据添加一个来伪造一个:

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

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

关于angular - NGRX 8 reducer 返回对象而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com