[Angular] NgRx/effect, why to use it?
See the current implementaion of code, we have a smart component, and inside the smart component we are using both 'serivce' and 'store'.
In the large application, what we really want is one service to handle the application state instead of two or more. And also we need response to the user action to get new data, all the requirements actaully can be handled by 'Store'.
import {Component, OnInit} from '@angular/core';
import {Store} from '@ngrx/store';
import {ThreadsService} from "../services/threads.service";
import {AppState} from "../store/application-state";
import {AllUserData} from "../../../shared/to/all-user-data";
import {LoadUserThreadsAction} from "../store/actions";
import {Observable} from "rxjs";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/skip';
import {values, keys, last} from 'ramda';
import {Thread} from "../../../shared/model/thread.interface";
import {ThreadSummary} from "./model/threadSummary.interface";
@Component({
selector: 'thread-section',
templateUrl: './thread-section.component.html',
styleUrls: ['./thread-section.component.css']
})
export class ThreadSectionComponent implements OnInit {
userName$: Observable<string>;
counterOfUnreadMessages$: Observable<number>;
threadSummary$: Observable<ThreadSummary[]>;
constructor(private store: Store<AppState>,
private threadsService: ThreadsService) {
this.userName$ = store.select(this.userNameSelector);
this.counterOfUnreadMessages$ = store.select(this.unreadMessageCounterSelector);
this.threadSummary$ = store.select(this.mapStateToThreadSummarySelector.bind(this))
}
mapStateToThreadSummarySelector(state: AppState): ThreadSummary[] {
const threads = values<Thread>(state.storeData.threads);
return threads.map((thread) => this.mapThreadToThreadSummary(thread, state));
}
mapThreadToThreadSummary(thread: Thread, state: AppState): ThreadSummary {
const names: string = keys(thread.participants)
.map(participantId => state.storeData.participants[participantId].name)
.join(', ');
const lastMessageId: number = last(thread.messageIds);
const lastMessage = state.storeData.messages[lastMessageId];
return {
id: thread.id,
participants: names,
lastMessage: lastMessage.text,
timestamp: lastMessage.timestamp
};
}
userNameSelector(state: AppState): string {
const currentUserId = state.uiState.userId;
const currentParticipant = state.storeData.participants[currentUserId];
if (!currentParticipant) {
return "";
}
return currentParticipant.name;
}
unreadMessageCounterSelector(state: AppState): number {
const currentUserId: number = state.uiState.userId;
if (!currentUserId) {
return ;
}
return values<Thread>(state.storeData.threads)
.reduce(
(acc: number, thread) => acc + (thread.participants[currentUserId] || )
, );
}
ngOnInit() {
this.threadsService.loadUserThreads()
.subscribe((allUserData: AllUserData) => {
this.store.dispatch(new LoadUserThreadsAction(allUserData))
});
}
}
So what we want to do to improve the code is to "remove the service from the component, let it handle by ngrx/effect" lib.
Here instead we call the service to get data, we will dispatch an action call 'LoadUserTreadsAction', and inside this action, will have side effect either "UserTreadsLoadSuccess" or "UserTreadsLoadError".
Create a effect service:
import {Injectable} from '@angular/core';
import {Action} from '@ngrx/store';
import {Actions, Effect} from "@ngrx/effects";
import {ThreadsService} from "../../services/threads.service";
import {LOAD_USER_THREADS_ACTION, LoadUserThreadsSuccess} from "../actions";
import {Observable} from "rxjs";
@Injectable()
export class LoadUserThreadsEffectService {
constructor(private action$: Actions, private threadsService: ThreadsService) {
}
@Effect()
userThreadsEffect$: Observable<Action> = this.action$
.ofType(LOAD_USER_THREADS_ACTION) // only react for LOAD_USER_THREADS_ACTION
.switchMap(() => this.threadsService.loadUserThreads()) // get data from service
.map((allUserData) => new LoadUserThreadsSuccess(allUserData)) // After get data, dispatch success action
}
And of course, we need to import the lib:
..
import {EffectsModule} from "@ngrx/effects";
import {LoadUserThreadsEffectService} from "./store/effects/load-user-threads.service"; @NgModule({
declarations: [
AppComponent
],
imports: [
..
EffectsModule.run(LoadUserThreadsEffectService),
],
providers: [
ThreadsService
],
bootstrap: [AppComponent]
})
export class AppModule {
}
We need to change reudcer, instead of add case for 'LOAD_USER_THREAD_ACTION', we should do 'LOAD_USER_THREADS_SUCCESS':
export function storeReducer(state: AppState = INITIAL_APPLICATION_STATE, action: Action): AppState {
switch(action.type) {
case LOAD_USER_THREADS_SUCCESS:
return handleLoadUserThreadsAction(state, action);
default:
return state;
}
}
Last, in our component, we dispatch 'LoadUserThreadsAction':
ngOnInit() {
this.store.dispatch(new LoadUserThreadsAction())
}
[Angular] NgRx/effect, why to use it?的更多相关文章
- [Angular] How to get Store state in ngrx Effect
For example, what you want to do is navgiate from current item to next or previous item. In your com ...
- [Angular] Ngrx/effects, Action trigger another action
@Injectable() export class LoadUserThreadsEffectService { constructor(private action$: Actions, priv ...
- ngRx 官方示例分析 - 6 - Effect
@ngrx/effect 前面我们提到,在 Book 的 reducer 中,并没有 Search 这个 Action 的处理,由于它需要发出一个异步的请求,等到请求返回前端,我们需要根据返回的结果来 ...
- [转]VS Code 扩展 Angular 6 Snippets - TypeScript, Html, Angular Material, ngRx, RxJS & Flex Layout
本文转自:https://marketplace.visualstudio.com/items?itemName=Mikael.Angular-BeastCode VSCode Angular Typ ...
- 手把手教你用ngrx管理Angular状态
本文将与你一起探讨如何用不可变数据储存的方式进行Angular应用的状态管理 :ngrx/store——Angular的响应式Redux.本文将会完成一个小型简单的Angular应用,最终代码可以在这 ...
- 如何在AngularX 中 使用ngrx
ngrx 是 Angular框架的状态容器,提供可预测化的状态管理. 1.首先创建一个可路由访问的模块 这里命名为:DemopetModule. 包括文件:demopet.html.demopet.s ...
- ngRx 官方示例分析 - 4.pages
Page 中通过构造函数注入 Store,基于 Store 进行数据操作. 注意 Component 使用了 changeDetection: ChangeDetectionStrategy.OnPu ...
- ngRx 官方示例分析 - 3. reducers
上一篇:ngRx 官方示例分析 - 2. Action 管理 这里我们讨论 reducer. 如果你注意的话,会看到在不同的 Action 定义文件中,导出的 Action 类型名称都是 Action ...
- angular版聊天室|仿微信界面IM聊天|NG2+Node聊天实例
一.项目介绍 运用angular+angular-cli+angular-router+ngrx/store+rxjs+webpack+node+wcPop等技术实现开发的仿微信angular版聊天室 ...
随机推荐
- 关于img标签的探讨
关于img标签的探讨:一直以来img属于那一种标签受到困惑,因为它既有块元素的特性也有行内元素的属性.它独占一行,也可以设置宽高. 在此重新学习一下标签元素的分类;html元素的分类:块元素.内联元素 ...
- 洛谷P3403跳楼机(最短路构造/同余最短路)
题目-> 解题思路: 最短路构造很神啊. 先用前两个值跑在第三个值模意义下的同余最短路(这步贪心可以证明,如果第三步长为z,那么如果n+z可以达到,n+2z同样可以达到) 最后计算与楼顶差多少个 ...
- Python Unittest模块测试执行
记录一下Unittest的测试执行相关的点 一.测试用例执行的几种方式 1.通过unittest.main()来执行测试用例的方式: if __name__ == "__main__&quo ...
- 【习题 7-2 UVA-225】Golygons
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 暴力枚举每次走哪里就好. 用一个二维数组来判重.(数据里,要求不能经过一个点两次->但路径可以相交 然后再用一个flag数组, ...
- COGS——C 908. 校园网 || 洛谷——P 2746 [USACO5.3]校园网Network of Schools
http://www.cogs.pro/cogs/problem/problem.php?pid=908 || https://www.luogu.org/problem/show?pid=27 ...
- 微信支付v2开发(1) 微信支付URL配置
本文介绍微信支付申请时如何设置授权目录及URL. 在申请微信支付时,第一项就会碰到下图的配置. 下面就对这一设置进行讲解! 一.选择支付类型 目前有两种支付类型 JS API网页支付 Native原生 ...
- JS实现时钟效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 学习笔记:Vue——混入
前言: 到现在用Vue做了不少项目了,用到的都是初阶的功能,很多高阶能力都没有用到.仅用初级阶段也能做项目,甚至是复杂项目,可见vue之强大,果然是渐进式开发方式. 但是本着虚心学习的态度,还是要抽空 ...
- 11.3 Android显示系统框架_最简单的surface测试程序
APP有一个surface(界面),其有多个buffer用来存放界面数据,这些buffer是向surfaceflinger申请的: 因此我们编写的surface测试程序步骤: (1)获得surface ...
- springboot入门(三)-- springboot集成mybatis及mybatis generator工具使用
前言 mybatis是一个半自动化的orm框架,所谓半自动化就是mybaitis只支持数据库查出的数据映射到pojo类上,而实体到数据库的映射需要自己编写sql语句实现,相较于hibernate这种完 ...