角度X中使用ngrx的方法详解(附源码)
前言
ngrx是有角的框架的状态容器,提供可预测化的状态管理。下面话不多说,来一起看看详细的介绍:
1.首先创建一个可路由访问的模块这里命名为:DemopetModule。
包括文件:demopet.html、demopet。SCS、demopet.component.ts、demopet.routes.ts、demopet.module.ts
代码如下:
demopet.html
!-暂时放一个标签- h1Demo/h1demopet.scss
h1 { color : # d 70029 } demo pet.component . ts
从“@棱角分明/核心”导入{组件};@ Component({选择器: ' demo-pet ',style URL 3360[)./演示宠物。SCS '],templateUrl: ' ./demoppet。html ' })导出类demope component {//现在什么都没有.}demopet.routes.ts
从""导入{ DemoPetComponent } ./演示宠物。组件';export const routes=[ { path: ' ',pathMatch: 'full ',children: [ { path: ' ',component : Demopetcomponent }]}];demopet.module.ts
从" @棱角分明/普通"导入{公共模块};从" @角形/形状"导入{窗体模块};从“@棱角分明/核心”导入{ ng module };从" @angular/router "导入{ RouterModule };从导入{路由} ./演示宠物。“路线”;@ ng模块({声明:[Demopetcomponent,],imports: [ CommonModule,FormsModule,RouterModule.forChild(routes) ],providers: [ ]})导出类DemoPetModule { }整体代码结构如下:
运行效果如下:只是为了学习方便,能够有个运行的模块
2.安装ngrx
NPM安装@ ngrx/core-保存NPM安装@ ngrx/store-保存NPM安装@ ngrx/effects-保存@ ngrx/store是一个旨在提高写性能的控制状态的容器
3.使用ngrx
首先了解下单向数据流形式
代码如下:
pet-tag.actions.ts
从“@棱角分明/核心”导入{内射};从" @ngrx/store "导入{操作};@可注射()导出类PettagActions { static LOAD _ DATA=' LOAD DATA ';load data(): action { return { type : pettagactions .LOAD _ DATA };}静态加载数据成功='加载数据成功;loadDtaSuccess(数据):操作{ return { type : pettagactions .LOAD_DATA_SUCCESS,有效载荷: DATA };}静态LOAD _ INFO=' LOAD InfoloadInfo():操作{ return { type : pettagactions .LOAD _ INFO };}静态加载信息成功='加载信息成功;loadInfoSuccess(数据):操作{ return { type : pettagactions .LOAD_INFO_SUCCESS,有效载荷:数据};}}pet-tag.reducer.ts
从" @ngrx/store "导入{操作};从“rxjs/天文台”导入{天文台};从导入{ PettagActions }./动作/宠物标签。动作';导出函数pettagreduce(状态: any,动作: action){ switch(动作。type){ case PettagActions .加载数据成功:{返回动作} //case PettagActions .LOAD _ INFO _ success : {//返回动作。有效载荷;//} default:{返回状态;} } }导出函数infoReducer(state:any,action : action){ switch(action。type){ case PettagActions .LOAD _ INFO _ success : {返回操作。有效载荷;} default:{返回状态;} } }注意:操作中定义了我们期望状态如何发生改变还原剂实现了状态具体如何改变
行动与商店之间添加ngrx/效果实现行为异步请求与商店处理结果间的解耦
宠物标签效果
从“@棱角分明/核心”导入{内射};从" @ngrx/effects "导入{效果,动作};从导入{ PettagActions }./动作/宠物标签。动作';从""导入{ PettagService }./服务/宠物标签。“服务”;@可注射()导出类PettagEffect {构造函数(私有操作:美元行动,私有pettagactions : pettagactions,私有service : pettagservice){ } @ Effect()load data=this。行动美元.类型(PettagActions .加载数据)。开关映射(()=this。服务。getdata()).地图(数据=这个。pettagaction。loadd tascess(data))@ Effect()loadInfo=this。行动美元.类型(PettagActions .加载信息).开关映射(()=this。服务。Getinfo()).地图(数据=这个。pettagaction。loadinfosuccess(数据));}4.修改demopet.module.ts添加ngrx支持
从" @ngrx/store "导入{存储模块};从" @ngrx/effects "导入{效果模块};从""导入{ PettagActions } ./动作/宠物标签。动作';从""导入{ petTagReducer,infoReducer } ./减压器/宠物标签。“减速器”;从""导入{ PettagEffect } ./效果/宠物标签。效果';@ ng模块({声明s :[Demopetcomponent,],导入s 3360[公共模块,FormsModule,RouterModule.forChild(routes),//此处新增存储模块。provide store({ pet : pettagreduce,info:infoReducer })、效果模块。run(PettagEffect)],providers: [ PettagActions,PettagService ]})导出类演示模块{ 5 } .调用ngrx实现数据列表获取与单个详细信息获取
demopet.component.ts
从“@棱角分明/核心”导入{组件,OnInit,ViewChild,after view init };从“rjs”导入{可观察到};从" @ngrx/store "导入{ Store };从" rxjs/订阅"导入{订阅};从""导入{ HttpService }./shared/services/http/http。“服务”;从""导入{ PetTag } ./型号/宠物标签。模型';从""导入{ PettagActions } ./动作/宠物标签。动作';@ Component({选择器: ' demo-pet ',style URL 3360[)./演示宠物。SCS '],templateUrl: ' ./demoppet。html ' })导出类Demopetcomponent {私有sub :订阅;公共数据Arr:任何;公共数据项:任何;公共语言:字符串=' enpublic param={ value : ' world ' };构造函数(private store: StorePetTag,private action : PettagActions){这。dataarr=store。选择('宠物');} NGoninit(){ this。商店。调度(这个。行动。LoadDATa());} NGondestroy(){ this。潜艇。unsubscribe();}信息(){控制台。日志('信息');这个。DataItem=这个。商店。选择('信息');这个。商店。调度(这个。行动。LoadInfo());}}demopet.html
h1 DEmo/h1 pre ul Li * ngFOr=' let d of DataArr | async ' DEmo : { { d . msg } }按钮(单击)=' info()' info/button/Li/ul { { DataItem | async | JSON } } h1 * ngFOr=' let d of DataItem | async ' { d . msg } }/h1/pre 6 .运行效果
初始化时候获取数据列表
点击信息按钮获取详细详细
7.以上代码是从项目中取出的部分代码,其中涉及到HttpService需要自己封装,data.json demo.json两个测试用的json文件,名字随便取的当时。
http.service.ts
从“@棱角分明/核心”导入{注入,注入};从" @angular/http "导入{ Http、Response、Headers、RequestOptions、urlsearchropms };从“rjs”导入{可观察到};导入”rxjs/add/operator/map”;导入“rxjs/运算符/延迟”;导入”rxjs/运算符/合并映射”;导入“rxjs/operator/SwitCh映射”;导入" rxjs/add/operator/catch ";导入“rxjs/add/observable/throw”;从""导入{ handleError } ./handleError ';从""导入{ rootPath } ./http。“config”;@可注射()导出类HttpServiCe { private _ root : string=' ';构造函数(私有Http :(Http){ this ._ root=ROOTPATH } public get(URL : string,data: Mapstring,any,root: string=this ._ root):可观察的ny { if(root==null)root=this ._ root let params=new urlsearchprams();if(!data) { data.forEach(函数(v,k) { params.set(k,v);});}返回this.http.get(根url,{ search: params }).map((resp : Response)=resp。JSON()).catch(handleError);}}8.模块源代码
下载地址
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对我们的支持。
版权声明:角度X中使用ngrx的方法详解(附源码)是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。