這篇文章主要介紹Angular X中如何使用ngrx,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:空間域名、虛擬主機(jī)、營銷軟件、網(wǎng)站建設(shè)、城廂網(wǎng)站維護(hù)、網(wǎng)站推廣。1.首先創(chuàng)建一個(gè)可路由訪問的模塊 這里命名為:DemopetModule。
包括文件:demopet.html、demopet.scss、demopet.component.ts、demopet.routes.ts、demopet.module.ts
代碼如下:
demopet.html
<!--暫時(shí)放一個(gè)標(biāo)簽--> <h2>Demo</h2>
demopet.scss
h2{ color:#d70029; }
demopet.component.ts
import { Component} from '@angular/core'; @Component({ selector: 'demo-pet', styleUrls: ['./demopet.scss'], templateUrl: './demopet.html' }) export class DemoPetComponent { //nothing now... }
demopet.routes.ts
import { DemoPetComponent } from './demopet.component'; export const routes = [ { path: '', pathMatch: 'full', children: [ { path: '', component: DemoPetComponent } ] } ];
demopet.module.ts
import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { routes } from './demopet.routes'; @NgModule({ declarations: [ DemoPetComponent, ], imports: [ CommonModule, FormsModule, RouterModule.forChild(routes) ], providers: [ ] }) export class DemoPetModule { }
整體代碼結(jié)構(gòu)如下:
運(yùn)行效果如下:只是為了學(xué)習(xí)方便,能夠有個(gè)運(yùn)行的模塊
2.安裝ngrx
npm install @ngrx/core --save npm install @ngrx/store --save npm install @ngrx/effects --save
@ngrx/store是一個(gè)旨在提高寫性能的控制狀態(tài)的容器
3.使用ngrx
首先了解下單向數(shù)據(jù)流形式
代碼如下:
pet-tag.actions.ts
import { Injectable } from '@angular/core'; import { Action } from '@ngrx/store'; @Injectable() export class PettagActions{ static LOAD_DATA='Load Data'; loadData():Action{ return { type:PettagActions.LOAD_DATA }; } static LOAD_DATA_SUCCESS='Load Data Success'; loadDtaSuccess(data):Action{ return { type:PettagActions.LOAD_DATA_SUCCESS, payload:data }; } static LOAD_INFO='Load Info'; loadInfo():Action{ return { type:PettagActions.LOAD_INFO }; } static LOAD_INFO_SUCCESS='Load Info Success'; loadInfoSuccess(data):Action{ return { type:PettagActions.LOAD_INFO_SUCCESS, payload:data }; } }
pet-tag.reducer.ts
import { Action } from '@ngrx/store'; import { Observable } from 'rxjs/Observable'; import { PettagActions } from '../action/pet-tag.actions'; export function petTagReducer(state:any,action:Action){ switch(action.type){ case PettagActions.LOAD_DATA_SUCCESS:{ return action.payload; } // case PettagActions.LOAD_INFO_SUCCESS:{ // return action.payload; // } default:{ return state; } } } export function infoReducer(state:any,action:Action){ switch(action.type){ case PettagActions.LOAD_INFO_SUCCESS:{ return action.payload; } default:{ return state; } } }
NOTE:Action中定義了我們期望狀態(tài)如何發(fā)生改變 Reducer實(shí)現(xiàn)了狀態(tài)具體如何改變
Action與Store之間添加ngrx/Effect 實(shí)現(xiàn)action異步請求與store處理結(jié)果間的解耦
pet-tag.effect.ts
import { Injectable } from '@angular/core'; import { Effect,Actions } from '@ngrx/effects'; import { PettagActions } from '../action/pet-tag.actions'; import { PettagService } from '../service/pet-tag.service'; @Injectable() export class PettagEffect { constructor( private action$:Actions, private pettagAction:PettagActions, private service:PettagService ){} @Effect() loadData=this.action$ .ofType(PettagActions.LOAD_DATA) .switchMap(()=>this.service.getData()) .map(data=>this.pettagAction.loadDtaSuccess(data)) @Effect() loadInfo=this.action$ .ofType(PettagActions.LOAD_INFO) .switchMap(()=>this.service.getInfo()) .map(data=>this.pettagAction.loadInfoSuccess(data)); }
4.修改demopet.module.ts 添加 ngrx支持
import { StoreModule } from '@ngrx/store'; import { EffectsModule } from '@ngrx/effects'; import { PettagActions } from './action/pet-tag.actions'; import { petTagReducer,infoReducer } from './reducer/pet-tag.reducer'; import { PettagEffect } from './effect/pet-tag.effect';
@NgModule({ declarations: [ DemoPetComponent, ], imports: [ CommonModule, FormsModule, RouterModule.forChild(routes), //here new added StoreModule.provideStore({ pet:petTagReducer, info:infoReducer }), EffectsModule.run(PettagEffect) ], providers: [ PettagActions, PettagService ] }) export class DemoPetModule { }
5.調(diào)用ngrx實(shí)現(xiàn)數(shù)據(jù)列表獲取與單個(gè)詳細(xì)信息獲取
demopet.component.ts
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core'; import { Observable } from "rxjs"; import { Store } from '@ngrx/store'; import { Subscription } from 'rxjs/Subscription'; import { HttpService } from '../shared/services/http/http.service'; import { PetTag } from './model/pet-tag.model'; import { PettagActions } from './action/pet-tag.actions'; @Component({ selector: 'demo-pet', styleUrls: ['./demopet.scss'], templateUrl: './demopet.html' }) export class DemoPetComponent { private sub: Subscription; public dataArr: any; public dataItem: any; public language: string = 'en'; public param = {value: 'world'}; constructor( private store: Store<PetTag>, private action: PettagActions ) { this.dataArr = store.select('pet'); } ngOnInit() { this.store.dispatch(this.action.loadData()); } ngOnDestroy() { this.sub.unsubscribe(); } info() { console.log('info'); this.dataItem = this.store.select('info'); this.store.dispatch(this.action.loadInfo()); } }
demopet.html
<h2>Demo</h2> <pre> <ul> <li *ngFor="let d of dataArr | async"> DEMO : {{ d.msg }} <button (click)="info()">info</button> </li> </ul> {{ dataItem | async | json }} <h2 *ngFor="let d of dataItem | async"> {{ d.msg }} </h2> </pre>
6.運(yùn)行效果
初始化時(shí)候獲取數(shù)據(jù)列表
點(diǎn)擊info按鈕 獲取詳細(xì)詳細(xì)
7.以上代碼是從項(xiàng)目中取出的部分代碼,其中涉及到HttpService需要自己封裝,data.json demo.json兩個(gè)測試用的json文件,名字隨便取的當(dāng)時(shí)。
http.service.ts
import { Inject, Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from "rxjs"; import 'rxjs/add/operator/map'; import 'rxjs/operator/delay'; import 'rxjs/operator/mergeMap'; import 'rxjs/operator/switchMap'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { handleError } from './handleError'; import { rootPath } from './http.config'; @Injectable() export class HttpService { private _root: string=""; constructor(private http: Http) { this._root=rootPath; } public get(url: string, data: Map<string, any>, root: string = this._root): Observable<any> { if (root == null) root = this._root; let params = new URLSearchParams(); if (!!data) { data.forEach(function (v, k) { params.set(k, v); }); } return this.http.get(root + url, { search: params }) .map((resp: Response) => resp.json()) .catch(handleError); } }
以上是“Angular X中如何使用ngrx”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站www.rwnh.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
新聞標(biāo)題:AngularX中如何使用ngrx-創(chuàng)新互聯(lián)
轉(zhuǎn)載來于:http://www.rwnh.cn/article28/csiocp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、服務(wù)器托管、網(wǎng)站制作、微信小程序、App設(shè)計(jì)、網(wǎng)站維護(hù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容