angular2+ 的學(xué)習(xí)成本應(yīng)該是三大框架中最高的一個,教程及案例稀缺,流程較為復(fù)雜,這里我用計數(shù)器和在線獲取用戶數(shù)據(jù)并渲染成列表這兩個案例來幫大家快速入手angular2+。
在開始之前,希望你能先掌握rxjs以及typescript,否則對其中的一些寫法可能會覺得難以理解。
在開始之前,需要先安裝@ngrx/store和@ngrx/effects
yarn add @ngrx/store @ngrx/effects
本教程使用的 ngrx/effects和ngrx/store版本均為5.2.0。
先來大致說一下開發(fā)流程:
開始 -> 編寫數(shù)據(jù)模型 -> 編寫action -> 編寫redurces并配置到相應(yīng)module -> 編寫services -> 編寫effects并配置到相應(yīng)module -> 創(chuàng)建組件 -> 組件綁定數(shù)據(jù)模型 -> 渲染
我們先完成計數(shù)器案例。此案例由于沒有異步任務(wù),所以可以省略掉services和effects。
從創(chuàng)建項目到啟動初始頁面之間的步驟這里就不講了。注意style要使用scss。還有不要使用cnpm安裝包。改用yarn或者npm,這樣后期使用不容易報錯。
ng new your-project --style scss
第一步:編寫數(shù)據(jù)模型(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 ],
第四部:創(chuàng)建組件
ng g component model-num
第五步:組件綁定數(shù)據(jù)模型(連帶完成第六步)
組件html文件:
<p> <input (click)="add()" value="+" type="button"> <p>{{num.count}}</p> <input value="-" type="button"> <br/> <a routerLink="/list">to list demo</a></p>
組件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({ //調(diào)用dispatch觸發(fā)添加redurces type: NumActionType.Add }); } ngOnInit() { } }
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
JavaScript之優(yōu)化DOM
Vue的計算屬性
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com