在Angular 5应用程序中显示Redux商店中的项目,你可以按照以下步骤进行操作:
app.state.ts
的文件,定义应用程序的状态接口。例如:export interface AppState {
projects: Project[];
}project.actions.ts
的文件,定义操作。例如:import { Action } from '@ngrx/store';
import { Project } from './project.model'; export enum ProjectActionTypes {
LoadProjects = '[Project] Load Projects',
AddProject = '[Project] Add Project',
RemoveProject = '[Project] Remove Project',
}
export class LoadProjects implements Action {
readonly type = ProjectActionTypes.LoadProjects;
constructor(public payload: Project[]) {}
}
export class AddProject implements Action {
readonly type = ProjectActionTypes.AddProject;
constructor(public payload: Project) {}
}
export class RemoveProject implements Action {
readonly type = ProjectActionTypes.RemoveProject;
constructor(public payload: string) {}
}
export type ProjectActions = LoadProjects | AddProject | RemoveProject;
```
project.reducer.ts
的文件,定义状态的更新逻辑。例如:import { Project } from './project.model';
import { ProjectActions, ProjectActionTypes } from './project.actions'; export interface ProjectState {
projects: Project[];
}
export const initialState: ProjectState = {
projects: [],
};
export function projectReducer(state = initialState, action: ProjectActions): ProjectState {
switch (action.type) {
case ProjectActionTypes.LoadProjects:
return { ...state, projects: action.payload };
case ProjectActionTypes.AddProject:
return { ...state, projects: [...state.projects, action.payload] };
case ProjectActionTypes.RemoveProject:
return { ...state, projects: state.projects.filter(project => project.id !== action.payload) };
default:
return state;
}
}
```
project.selectors.ts
的文件,定义选择器用于从状态中选择特定的数据。例如:import { createSelector } from '@ngrx/store';
import { AppState } from '../app.state';
import { ProjectState } from './project.reducer'; export const selectProjectState = (state: AppState) => state.projects;
export const selectAllProjects = createSelector(
selectProjectState,
(state: ProjectState) => state.projects
);
```
Store
服务和相关的操作。例如:import { Store } from '@ngrx/store';
import { LoadProjects, AddProject, RemoveProject } from './project.actions';
import { selectAllProjects } from './project.selectors'; constructor(private store: Store) {}
```
ngOnInit
生命周期钩子中,使用Store
服务来调度操作并选择所需的数据。例如:ngOnInit() {
this.store.dispatch(new LoadProjects()); // 调度加载项目的操作
this.projects$ = this.store.select(selectAllProjects); // 选择所有项目的数据
}async
管道来订阅并显示项目数据。例如:<ul>
<li *ngFor="let project of projects$ | async">{{ project.name }}</li>
</ul>这样,你就可以在Angular 5应用程序中显示Redux商店中的项目了。请注意,上述代码仅为示例,你需要根据你的实际需求进行适当的修改和调整。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云对象存储(COS)。
领取专属 10元无门槛券
手把手带您无忧上云