标签的NgRx存储状态

时间:2018-10-25 12:59:02

标签: angular angular6 ngrx

我正在尝试在应用程序中实现类似于浏览器选项卡的功能。目前,我正在商店中为每个打开的标签创建一个新密钥,并分别存储当前标签的ID。目前,我商店的状态与此类似:

{
  currentTab: 0,
  0: {
       url: 'http://google.com'
  }
  1: {
       url: 'http://twitter.com'
  }
}

由于我是ngrx的新手,所以我希望您能说出这是否是解决此类问题的正确方法。

非常感谢!

1 个答案:

答案 0 :(得分:1)

您实际上应该将标签存储在@ngrx/entity中。 UI状态绝对属于商店,请参见here

您的减速器看起来像

import { createEntityAdapter, EntityState } from '@ngrx/entity';

import { TabsActions, TabsActionTypes } from '../actions';
import { Tab } from '../../models/tab';

export const adapter = createEntityAdapter<Tab>({
  selectId: tab => tab.id,
  sortComparer: (tabA, tabB) => tabA.id === tabB.id ? 0 : tabA.id > tabB.id ? 1 : -1
});

export interface State extends EntityState<Tab> {
  currentTab: number
}
export const initialState = adapter.getInitialState({
  currentTab: 0
});

export function reducer(state = initialState, action: TabsActions) {
  switch (action.type) {
    case TabsActionTypes.Add:
      return adapter.add(action.payload, state);

    case TabsActionTypes.Close:
      return adapter.remove(action.payload, state);

    case TabsActionTypes.SwitchTab:
      return { ...state, currentTab: action.payload }

    default:
      return state;
  }
}

将动作定义为

import { Action } from '@ngrx/store';
import { Tab } from '../../models/tab';

export enum TabsActionTypes {
  Add = '[Tabs] Add',
  Close= '[Tabs] Close',
  SwitchTab = '[Tabs] Switch'
}

export class AddTab implements Action {
  readonly type = TabsActionTypes.Add;
  constructor(public payload: Tab) {}
}

// Define other actions (CloseTab, SwitchTab) in a similar way

export type TabsActions =
  AddTab |
  CloseTab |
  SwitchTab;