zoukankan      html  css  js  c++  java
  • [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 fetchoptimisticUpdate, 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:

    
    
    import { NxModule } from '@nrwl/nx';
      
    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);
                }
            }
        );
    }
  • 相关阅读:
    TypeScript
    Jmeter注册100个账户的三个方法
    Jmeter之cookie处理的2中方法
    Jmeter_JsonPath 提取器
    Jmeter_正则表达式提取器_提取数组 & For Each 控制器
    Jmeter_正则表达式提取器_提取单组数据
    Jmeter_选项_函数助手_RandomString的用法
    Jmeter_正则表达式
    Jmeter_选项_函数助手对话框_CSVRead
    Jmeter_请求原件之参数化CSV
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10340262.html
Copyright © 2011-2022 走看看