使用Redux和Behavior Subject进行angular 5状态管理

时间:2018-07-25 19:12:37

标签: angular5 angular6 state-management

如何在角度5中进行状态管理?在Redux和Behavior Subject之间,哪种方法更好,为什么?

谢谢。

1 个答案:

答案 0 :(得分:0)

relevant

ngrx示例示例

安装以下软件包:

  • npm install @ ngrx / store --save

  • npm install @ ngrx / effects --save

  • app.module.ts


import { appReducer } from './state/app.reducer';
import { StoreModule } from '@ngrx/store';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
   ...

    StoreModule.forRoot(appReducer)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState } from './state/app.state';
import { SetAppTitleAction, getAppTitle } from './state/app-title';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  template:
    `<h1>{{appTitle$ | async}}</h1>
    `
})
export class AppComponent implements OnInit {
  appTitle$: Observable<string>;
  constructor(private store: Store<AppState>) {
    this.appTitle$ = this.store.select(getAppTitle);
  }
  ngOnInit(): void {
    this.store.dispatch(new SetAppTitleAction('Location: AppComponent'));
  }
}

app-title.action.ts

import { Action } from '@ngrx/store';

export const SetAppTitle = 'Set App Title';

export class SetAppTitleAction implements Action {
  readonly type = SetAppTitle;
  constructor(public payload: string) {}
}

export type AppTitleActions = SetAppTitleAction;

app-title.reducer.ts

import { AppTitleActions, SetAppTitle } from './app-title.actions';

export function appTitleReducer(state: string, action: AppTitleActions) {
  switch (action.type) {
    case SetAppTitle:
      return action.payload;
    default: return state;
  }
}

index.ts

export * from './app-title.actions';
import { AppState } from './app.state';

export const getState = (state: AppState) => state;
export const getAppTitle = createSelector(getState, state => state.appTitle);

app.reducer.ts

import { ActionReducerMap } from '@ngrx/store';
import { AppState } from './app.state';
import { appTitleReducer } from './app-title/app-title.reducer';
import { versionInfoReducer } from './version-info/version-info.reducer';

export const appReducer: ActionReducerMap<AppState> = {
    appTitle: appTitleReducer
};


export interface AppState {
    appTitle: string;
}