当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ngrx/store effects 使用总结1:计数器

ngrx/store effects 使用总结1:计数器

2018年03月17日  | 移动技术网IT编程  | 我要评论

 

本教程案例github:https://github.com/axel10/ngrx_demo-counter-and-list

angular2+ 的学习成本应该是三大框架中最高的一个,教程及案例稀缺,流程较为复杂,这里我用计数器和在线获取用户数据并渲染成列表这两个案例来帮大家快速入手angular2+。

 

在开始之前,希望你能先掌握rxjs以及typescript,否则对其中的一些写法可能会觉得难以理解。

rxjs英文向导:

rxjs中文向导:

typescipt w3cschool教程:https://www.w3cschool.cn/typescript/

 

在开始之前,需要先安装@ngrx/store和@ngrx/effects

yarn add @ngrx/store @ngrx/effects

本教程使用的 ngrx/effects和ngrx/store版本均为5.2.0。

 

先来大致说一下开发流程:

开始 -> 编写数据模型 -> 编写action -> 编写redurces并配置到相应module -> 编写services -> 编写effects并配置到相应module -> 创建组件 -> 组件绑定数据模型 -> 渲染

 

我们先完成计数器案例。此案例由于没有异步任务,所以可以省略掉services和effects。

从创建项目到启动初始页面之间的步骤这里就不讲了。注意style要使用scss。还有不要使用cnpm安装包。改用yarn或者npm,这样后期使用不容易报错。

ng new your-project --style scss

 

第一步:编写数据模型(app/models/num.ts)

export class Num {

  count: number;

 

  constructor(num: number) {

    this.count = num;

  }

}

 

第二步:编写action(app/actions/num.ts)

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

 

export enum NumActionType {

  Add = 'ADD'

}

 

export class ADD implements Action {

  readonly type = NumActionType.Add;  //固定写法,必须叫type

}

 

第三步:编写redurcers(app/redurces/modelNum.ts)

import {Num} from '../models/num';

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

import {NumActionType} from '../actions/num';

 

 

export const modelNum = (state: Num = new Num(0), action: Action) => {       

  switch (action.type) {

    case NumActionType.Add:

      state.count++;

      return state;

    default:

      return state;

  }

};

 

不要忘记配置redurcer(app/app.module.ts)

  imports: [

    BrowserModule,

    RouterModule.forRoot(routes),

    StoreModule.forRoot({ modelNum}),      //配置redurcer

  ],

 

 

第四部:创建组件

ng g component model-num

第五步:组件绑定数据模型(连带完成第六步)

组件html文件:

<div>

  <input (click)="add()" value="+" type="button">

  <p>{{num.count}}</p>

  <input value="-" type="button">

  <br/>

  <a routerLink="/list">to list demo</a>

</div>

 

组件ts文件:

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

import {Num} from '../models/num';

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

import {NumActionType} from '../actions/num';

@Component({

  selector: 'app-model-demo',

  templateUrl: './model-demo.component.html',

  styleUrls: ['./model-demo.component.scss']

})

export class ModelDemoComponent implements OnInit {

 

  constructor(private _store: Store<any>) {

    this._store.select('modelNum').subscribe(mNum => {    //涉及到rxjs。    

      this.num = mNum;

      console.log(mNum);

    });

  }

 

  public num: Num;

 

  public add() {

    console.log('add');

    this._store.dispatch({          //调用dispatch触发添加redurces

      type: NumActionType.Add

    });

  }

 

  ngOnInit() {

  }

 

}

 

 

 

完成相应的路由配置后,计数器案例完成。

现在开始案例2:在线获取用户列表并展示。

 http://www.cnblogs.com/axel10/p/8589139.html

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网