[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 0; } return values<Thread>(state.storeData.threads) .reduce( (acc: number, thread) => acc + (thread.participants[currentUserId] || 0) , 0); } 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()) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具