创建已下文件:
index.ts
export * from './video-gis.selector';
export * from './video-gis.actions';
export * from './video-gis.reducer';
export * from './video-gis.module';
video-gis.actions.ts
import { Action } from '@ngrx/store';
import {VideoInfo } from './video-gis.reducer';
export enum ActionTypes {
SetVideoInfo = '[Video GIS] Set Video Info', // 编辑视频信息
AddVideoInfo = '[Video GIS] Add Video Info', // 添加视频信息
UpdateVideoInfo = '[Video GIS] Update Video Info', // 更新视频信息
DeleteVideoInfo = '[Video GIS] Delete Video Info', // 删除视频信息
}
export class SetVideoInfo implements Action {
readonly type = ActionTypes.SetVideoInfo;
constructor(public payload: VideoInfo[]) { }
}
export class AddVideoInfo implements Action {
readonly type = ActionTypes.AddVideoInfo;
constructor(public payload: VideoInfo) { }
}
export class UpdateVideoInfo implements Action {
readonly type = ActionTypes.UpdateVideoInfo;
constructor(public payload: VideoInfo) { }
}
export class DeleteVideoInfo implements Action {
readonly type = ActionTypes.DeleteVideoInfo;
constructor(public index: number) { }
}
export type ActionUnion =
SetVideoInfo |
AddVideoInfo |
DeleteVideoInfo |
UpdateVideoInfo ;
video-gis.module.ts
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import {VideoInfoReducer } from './video-gis.reducer';
@NgModule({
imports: [
StoreModule.forFeature('videoInfo', VideoInfoReducer)
]
})
export class VideoGISModule { }
video-gis.reducer.ts
import { AppState } from '../app.state';
import * as Actions from './video-gis.actions';
export interface VideoInfo {
id: string;
name: string;
show: boolean;
data: any;
}
export interface State extends AppState {
videoInfo: VideoInfo[];
}
export const initialVideoInfoState: VideoInfo[] = videoInfoListData; // 默认值
export function VideoInfoReducer(
state = initialVideoInfoState,
action: Actions.ActionUnion
): VideoInfo[] {
console.log(action.type);
switch (action.type) {
case Actions.ActionTypes.SetVideoInfo:
return action.payload;
case Actions.ActionTypes.AddVideoInfo: {
const _state = state ? [...state] : [];
_state.push(action.payload as VideoInfo);
return _state;
}
case Actions.ActionTypes.DeleteVideoInfo: {
const _state = [...state];
_state.splice(action.index, 1);
return _state;
}
case Actions.ActionTypes.UpdateVideoInfo: {
const _state = [...state];
const idx = state.findIndex(path => path.name === action.payload.name);
_state[idx] = action.payload;
return _state;
}
default:
return state;
}
}
video-gis.selector.ts
import { createFeatureSelector } from '@ngrx/store';
import { State, VideoInfo } from './video-gis.reducer';
export const selectVideoInfo = createFeatureSelector<State, VideoInfo[]>('videoInfo');
使用:
在对应的componenet中:
public videoInfos: VideoInfo[];
constructor(private store: Store<AppState>) {
// 获取视频列表
this.store.pipe(select(selectVideoInfo)).subscribe(data => {
this.videoInfos = data || [];
});
}
// 使用方法
saveVideoInfoState(){
this.store.dispatch(new SetVideoInfo(this.videoInfos));
}