(精华2020年6月21日更新)Angular实战篇 ngrx/store状态管理的使用

首先自然是安装相关包

yarn add @ngrx/store

定义statu.ts

export interface TaskList {
  id: number;
  text: string;
  completed: boolean;
}

//初始状态
export const initCount = 0;   //state 

export const TASKSAll: TaskList[] = [
  { id: 1, text: 'C#', completed: false },
  { id: 2, text: '.net', completed: false }
]

export interface AppState {
  count: number;
  todos: TaskList;
}

定义reducer.ts

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

import { TASKSAll, initCount } from './state';


// reducer定义了action被派发时state的具体改变方式
export function counterReducer(state: number = initCount, action: Action) {

  switch (action.type) {
    case 'INCREMENT':
      return state + 1;

    case 'DECREMENT':
      return state - 1;

    case 'RESET':
      return 0;

    default:
      return state;
  }
}

// reducer定义了action被派发时state的具体改变方式

export const todoReducer = (state = TASKSAll, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      const { id, text } = action.payload;
      return [...state, {
        id,
        text,
        completed: false
      }];
    case 'TOGGLE_TODO':
      return state.map(todo =>
        (todo.id === action.payload.id)
          ? { ...todo, completed: !todo.completed }
          : todo
      )
    default:
      return state;
  }
}

在app.module.ts导入

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { StoreModule } from '@ngrx/store';
import {counterReducer,todoReducer} from './store/reducer';
import {FormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {UserModule} from './module/user/user.module';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    UserModule,
    FormsModule,
    StoreModule.forRoot({
      count:counterReducer,
      todos:todoReducer
    })
    //注册store
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在组件中使用

import { Component, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';

// interface AppState {
//   count:number
// }

import { AppState } from '../../store/state';
@Component({
  selector: 'app-article',
  templateUrl: './article.component.html',
  styleUrls: ['./article.component.less']
})


export class ArticleComponent implements OnInit {
  count: any;
  todolist: any;
  mytask: string = 'oppp';
  constructor(private store: Store<AppState>) {
    var stream = store.pipe(select('count'));

    var streamto = store.pipe(select('todos'));

    stream.subscribe((res) => {
      console.log(res)
      this.count = res;
    })

    streamto.subscribe((res) => {
      this.todolist = res;
    })
  }  //注入store
  ngOnInit(): void {

  }
  increment() {
    this.store.dispatch({
      type: 'INCREMENT',
      payload: {
        test: 4
      }
    })
  }
  decrement() {
    this.store.dispatch({
      type: 'DECREMENT',
      payload: {
        test: 1
      }
    })
  }
  reset() {
    this.store.dispatch({
      type: 'RESET',
      payload: {
        test: 1
      }
    })
  }
  addTask() {
    this.store.dispatch({
      type: 'ADD_TODO',
      payload: { id: 10, text: 'vue', completed: false }
    })
  }
}
<div class="state">
    <button type="button" (click)='increment()'>增加count</button>
    <div>current count: 
        
        <!-- {{count | async}} -->
      
        {{count}}

    </div>
    <button type="button" (click)='decrement()'>减少count</button>
</div>

todolist:
{{todolist | json}}

<ul>
    <li *ngFor="let item of todolist">

        {{item.text}}
    </li>
</ul>

新增:
<input type="text" [(ngModel)]="mytask">
<button type="button" (click)='addTask()'>新增任务</button>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页