首页 > 代码库 > [Angular] NgRx/effect, why to use it?
[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()) }
Github
[Angular] NgRx/effect, why to use it?