[Angular] Improve Server Communication in Ngrx Effects with NX Data Persistence in Angular
Communicating with a remote server via HTTP presents an extra level of complexity as there is an increased chance of race conditions and the need for error handling. There is also the tricky problem of how to handle the user experience as the application is trying to complete the remote request. NX Data Persistence is a library that works with ngrx effects to give us a better way to handle remote server calls as well as improving on the overall shape of the effect itself. In this lesson, we are going to convert our stock effects to use NX Data Persistence and the advantages of doing so by using fetch
, optimisticUpdate
, and pessimisticUpdate
. We will also see how it gives us a neat division in our effect to handle the sequence we want to run as well as any errors that should arise in the process.
Install:
npm i --save @nrwl/nx
app.module.ts:
imports: [
...
NxModule.forRoot(),
...
],
effect:
import { Injectable } from '@angular/core'; import {Effect} from '@ngrx/effects'; import { DataPersistence } from '@nrwl/nx'; import {Action} from '@ngrx/store'; import { RolesService } from '../services/roles.service'; import { Observable } from 'rxjs'; import { switchMap, map } from 'rxjs/operators'; import * as actions from '../actions'; import { Role } from '../models'; import { DashbaordState } from '../reducers'; @Injectable() export class RolesEffects { constructor( private rolesService: RolesService, private dataPersistence: DataPersistence<DashbaordState> ) { } @Effect() loadRoles$: Observable<Action> = this.dataPersistence.fetch( actions.RolesActionTypes.LoadRoles, { run: (action: actions.LoadRoles) => { return this.rolesService.roles.pipe( map((roles: Role[]) => new actions.LoadRolesSuccess(roles)) ); }, onError: (action: actions.LoadRoles, error) => { console.error('Error', action, error); } } ); }
相关文章
- Angular 里 HTTP 请求和响应结构的拦截器(interceptors)在 SAP Spartacus 中的应用
- 关于 Angular HttpClient 的单例特性的思考
- Angular面试题_session面试题
- angular 路由懒加载_angular路由
- 解决angular创建项目报错:setTimeout is not defined
- Angular Feature Modules
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- Angular 应用 tsconfig.json 文件里的 typeRoots 属性讲解
- 基于 Spartacus 的 Angular Storefront 性能优化建议
- Angular和jQuery的区别
- 微软与 Google 将共同打造 Angular 2
- 和 sql server支持两者:Oracle 和 SQL Server的兼容性(兼容oracle)
- MySQL 中 Server 的重要性(mysql中server)
- 甲,打败SQL Server乙超级武装Oracle甲战胜SQL server乙(exp 武装oracle)