使用ngrx6.0.1来管理Angular应用的数据状态

发布日期 目录 Angular

使用ngrx6.0.1来管理Angular应用的数据状态

ngrx的来源于redux,所以需要了解下redux相关的知识:state、action、reducer、store,百度了解下干什么用的,不会用没关系,本文章就通过最最基础的用法来记录下如何使用ngrx管理应用状态。当然实际中比这复杂多了。

相关版本:
ngrx:6.0.1
angular-cli:6.0.8

本文从两方面来
1、先创建ngrx项目在配置需要的目录
2、开始使用ngrx

项目描述:添加与删除用户的一个小项目

一、创建项目

安装angular-cli6.0.8
npm install -g @angular/cli@6.0.8

创建项目
ng new tutorial

进入项目安装ngrx,执行命令
npm install --save @ngrx/store@6.0.1

在app目录下创建models目录,在该目录里面创建 tutorial.model.ts文件,并复制以下内容:

export interface Tutorial {
  name: string;
  url: string;
}

然后创建actions目录,在该目录里面创建 toturial.actions.ts文件,并复制以下内容:

import { Action } from '@ngrx/store'
import { Tutorial } from '../models/tutorial.model'

export const ADD_TUTORIAL = '[TUTORIAL] add';
export const REMOVE_TUTORIAL = '[TUTORIAL] remove';

export class AddTutorial implements Action {
  readonly type = ADD_TUTORIAL;
  constructor(public payload: Tutorial) {}
}

export class RemoveTutorial implements Action {
  readonly type = REMOVE_TUTORIAL;
  constructor(public payload: number) {}
}

export type TutorialActions = AddTutorial | RemoveTutorial;

然后创建reduces目录,在该目录里面创建 tutorial.reducers.ts文件,并复制以下内容:

import { Tutorial } from '../models/tutorial.model'
import * as TutorialActions from '../actions/toturial.actions'

// 初始化数据值
const initialState: Tutorial = {
  name: 'seebin',
  url: 'http://blog.seebin.com'
}

// 累计器
export function reducer(state: Tutorial[] = [initialState], action: TutorialActions.TutorialActions) {
  console.log('reducer>state:', state)
  console.log('reducer>action:', action)
  switch (action.type) {
    case TutorialActions.ADD_TUTORIAL:
      return [...state, action.payload];

    case TutorialActions.REMOVE_TUTORIAL:
      state.splice(action.payload, 1)
      return state;

    default:
      return state;
  }
}

然后在app目录下创建turorial.state.ts文件,并复制一下内容:

import { Tutorial } from './models/tutorial.model'

export interface AppState {
  readonly tutorial: Tutorial[];
}

然后在app.module.ts文件中初始化ngrx

...
import { StoreModule } from '@ngrx/store';
import { reducer } from './reduces/tutorial.reducers'
...

...
imports: [
    ...
    StoreModule.forRoot({
      tutorial: reducer
    })
  ],
...

接下来创建组件来使用ngrx管理状态

创建两个组件read与create:
ng g c read
ng g c create

修改app.component.html 来加载这两个组件

<app-create></app-create>
<app-read></app-read>

修改read.component.ts文件,复制以下内容:

import { Component, OnInit } from '@angular/core';

import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { Tutorial } from '../models/tutorial.model';
import { AppState } from '../turorial.state';
import * as TutorialActions from '../actions/toturial.actions';

@Component({
  selector: 'app-read',
  templateUrl: './read.component.html',
  styleUrls: ['./read.component.css']
})
export class ReadComponent implements OnInit {
  // 监听数据状态
  tutorials: Observable<Tutorial[]>;

  constructor(private store: Store<AppState>) {
    // 选择一个store为tutorial名字
    this.tutorials = store.select('tutorial');
  }

  ngOnInit() {
  }
  // 点击用户删除方法
  delTutorial(index) {
    this.store.dispatch(new TutorialActions.RemoveTutorial(index))
  }
}

接下来

<div *ngIf='tutorials'>
  <h3>Tutorials</h3>
  <ul>
    <!-- async 必须有,否则收不到数据了 -->
    <li (click)="delTutorial(i)" *ngFor="let tutorial of tutorials | async;let i = index">
      <a [href]="tutorial.url">{{tutorial.name}}</a>
    </li>
  </ul>
</div>

这个时候ng serve启动项目应该可以在页面中看到我们在tutorial.reducers.ts里面设置的初始化的数据了,而且点击该用户还能删除该用户。

接下来修改create组件来增加添加用户的功能

修改create.component.ts文件,复制以下内容:

import { Component, OnInit } from '@angular/core';

import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { Tutorial } from '../models/tutorial.model';
import { AppState } from '../turorial.state';
import * as TutorialActions from '../actions/toturial.actions';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  constructor(private store: Store<AppState>) { }

  ngOnInit() {
  }
  // 向store派发添加的数据
  addTutorial(name, url) {
    this.store.dispatch(new TutorialActions.AddTutorial({ name: name, url: url }))
  }
}

接着修改create.component.html文件:

<div>
  <input type="text" #name>
  <input type="text" #url>
  <button (click)="addTutorial(name.value,url.value)">create</button>
</div>

好了,这个时候启动项目便可以添加用户与删除用户,代码很简单,但是却建了很多与tore相关的文件

项目代码地址:
seebin/ng-ngrx6.0.1

不同分支对应不同的功能:
最最基础的例子 store
https://gitee.com/seebin/ng-ngrx6.0.1/tree/master/

一个浏览器扩展工具devtools,可进行时间旅行,查看状态树等操作
https://gitee.com/seebin/ng-ngrx6.0.1/tree/devtools/

store-core
https://gitee.com/seebin/ng-ngrx6.0.1/tree/store-core/

参考资料:
ngrx tutorial(需科学上网)

发表评论

邮箱地址不会被公开。