ngrx /特效库的目的是什么?

时间:2016-09-17 21:49:37

标签: javascript angular typescript redux ngrx

我未能找到有关此库的任何有用信息或其目的是什么。 似乎ngrx/effects向已经了解这个概念的开发人员解释了这个库,并提供了一个关于如何编码的更大的例子。

我的问题:

  1. 什么是行动来源?
  2. ngrx / effects库的目的是什么;仅使用ngrx / store的缺点是什么?
  3. 什么时候建议使用?
  4. 是否支持角度rc 5+?我们如何在rc 5 +中配置它?
  5. 谢谢!

1 个答案:

答案 0 :(得分:90)

主题太广了。它就像一个教程。无论如何我会尝试一下。在正常情况下,您将拥有一个动作,减速器和一个商店。商店将调度操作,由reducer订阅。然后,reducer对动作起作用,并形成一个新状态。在示例中,所有状态都在前端,但在实际应用中,它需要调用后端DB或MQ等,这些调用具有副作用。用于将这些影响分解为一个共同点的框架。

假设您将人员记录保存到数据库action: Action = {type: SAVE_PERSON, payload: person}。通常,您的组件不会直接调用this.store.dispatch( {type: SAVE_PERSON, payload: person} )让reducer调用HTTP服务,而是调用this.personService.save(person).subscribe( res => this.store.dispatch({type: SAVE_PERSON_OK, payload: res.json}) )。添加实际生活错误处理时,组件逻辑将变得更加复杂。为了避免这种情况,只需打电话就可以了 来自您组件的this.store.dispatch( {type: SAVE_PERSON, payload: person} )

这就是效果库的用途。它在减速器前面就像一个JEE servlet过滤器。它匹配ACTION类型(过滤器可以匹配java世界中的url)然后对其进行操作,最后返回不同的操作,或者不执行任何操作或多个操作。然后,reducer响应效果的输出动作。

使用效果库继续上一个示例:

@Effects() savePerson$ = this.stateUpdates$.whenAction(SAVE_PERSON)
   .map<Person>(toPayload)
   .switchMap( person => this.personService.save(person) )
   .map( res => {type: SAVE_PERSON_OK, payload: res.json} )
   .catch( e => {type: SAVE_PERSON_ERR, payload: err} )

编织逻辑集中到所有Effects和Reducers类中。它可以轻松地变得更加复杂,同时这种设计使其他部件更加简单和可重复使用。

例如,如果UI具有自动保存加手动保存,为避免不必要的保存,UI自动保存部分只能由计时器触发,手动部分可以通过用户点击触发。两者都会调度SAVE_CLIENT操作。效果拦截器可以是:

@Effects() savePerson$ = this.stateUpdates$.whenAction(SAVE_PERSON)
   .debounce(300).map<Person>(toPayload)
   .distinctUntilChanged(...)
   .switchMap( see above )
   // at least 300 milliseconds and changed to make a save, otherwise no save

电话

...switchMap( person => this.personService.save(person) )
   .map( res => {type: SAVE_PERSON_OK, payload: res.json} )
   .catch( e => Observable.of( {type: SAVE_PERSON_ERR, payload: err}) )
如果出现错误,

仅适用一次。抛出错误后流已经死了因为catch尝试外部流。电话应该是

...switchMap( person => this.personService.save(person)
   .map( res => {type: SAVE_PERSON_OK, payload: res.json} )
   .catch( e => Observable.of( {type: SAVE_PERSON_ERR, payload: err}) ) )

或者另一种方式:更改所有ServiceClass服务方法以返回ServiceResponse,其中包含来自服务器端的错误代码,错误消息和包装的响应对象,即

export class ServiceResult {    
    error:     string;    
    data:      any;

    hasError(): boolean {
       return error != undefined && error != null;    }

    static ok(data: any): ServiceResult {
       let ret = new ServiceResult();
       ret.data = data;
       return ret;    
    }

    static err(info: any): ServiceResult {
       let ret = new ServiceResult();
       ret.error = JSON.stringify(info);
       return ret;    
   } 
}

@Injectable()
export class PersonService {
   constructor(private http: Http) {}
   savePerson(p: Person): Observable<ServiceResult> {
       return http.post(url, JSON.stringify(p)).map(ServiceResult.ok);
              .catch( ServiceResult.err ); 
   }
}

@Injectable()
export class PersonEffects {
  constructor(
    private update$: StateUpdates<AppState>,
    private personActions: PersonActions,
    private svc: PersonService
  ){
  }

@Effects() savePerson$ = this.stateUpdates$.whenAction(PersonActions.SAVE_PERSON)
   .map<Person>(toPayload)
   .switchMap( person => this.personService.save(person) )
   .map( res => {
       if (res.hasError()) {
           return personActions.saveErrAction(res.error);
       } else {
           return personActions.saveOkAction(res.data);
       }
   });

@Injectable()
export class PersonActions {
    static SAVE_OK_ACTION = "Save OK";
    saveOkAction(p: Person): Action {
       return {type: PersonActions.SAVE_OK_ACTION,
               payload: p};
    }

    ... ...
}

对我之前评论的一个修正:Effect-Class和Reducer-Class,如果你同时对Effect-class和Reducer-class做出反应,则Reducer-class将首先做出反应,然后是Effect-class。这是一个例子: 一个组件有一个按钮,一旦点击,名为:this.store.dispatch(this.clientActions.effectChain(1));,将由effectChainReducer处理,然后ClientEffects.chainEffects$,将有效负载从1增加到2;等待500毫秒发出另一个动作:this.clientActions.effectChain(2),由effectChainReducer处理,有效载荷= 2,然后ClientEffects.chainEffects$,从2增加到3,发出this.clientActions.effectChain(3) ,. ..,直到大于10,ClientEffects.chainEffects$发出this.clientActions.endEffectChain(),通过effectChainReducer将商店状态更改为1000,最后停在此处。

    export interface AppState {
      ... ...

      chainLevel:     number;
    }

    // In NgModule decorator
    @NgModule({
       imports: [...,
            StoreModule.provideStore({
                ... ...
                chainLevel: effectChainReducer
              }, ...],
       ...
       providers: [... runEffects(ClientEffects) ],
       ...
    })
    export class AppModule {}


    export class ClientActions {
      ... ...
      static EFFECT_CHAIN = "Chain Effect";
      effectChain(idx: number): Action {
        return {
              type: ClientActions.EFFECT_CHAIN,
              payload: idx
        };
      }

      static END_EFFECT_CHAIN = "End Chain Effect";
      endEffectChain(): Action {
        return {
          type: ClientActions.END_EFFECT_CHAIN,
        };
      }

  static RESET_EFFECT_CHAIN = "Reset Chain Effect";
  resetEffectChain(idx: number = 0): Action {
    return {
      type: ClientActions.RESET_EFFECT_CHAIN,
      payload: idx
    };

    }

    export class ClientEffects {
      ... ...
      @Effect()
      chainEffects$ = this.update$.whenAction(ClientActions.EFFECT_CHAIN)
        .map<number>(toPayload)
        .map(l => {
          console.log(`effect chain are at level: ${l}`)
          return l + 1;
        })
        .delay(500)
        .map(l => {
          if (l > 10) {
             return this.clientActions.endEffectChain();
          } else {
             return this.clientActions.effectChain(l);
          }
        });
    }

    // client-reducer.ts file
    export const effectChainReducer = (state: any = 0, {type, payload}) => {
      switch (type) {
        case ClientActions.EFFECT_CHAIN:
          console.log("reducer chain are at level: " + payload);
          return payload;
        case ClientActions.RESET_EFFECT_CHAIN:
          console.log("reset chain level to: " + payload);
          return payload;
        case ClientActions.END_EFFECT_CHAIN:
          return 1000;
        default:
          return state;
      }
    }

如果运行上面的代码,输出应如下所示:

  

client-reducer.ts:51减速机链处于等级:1
  client-effects.ts:72效果链处于等级:1
  client-reducer.ts:51减速机链处于等级:2
  client-effects.ts:72效果链处于等级:2
  client-reducer.ts:51减速机链处于等级:3
  client-effects.ts:72效果链处于等级:3
  ...... ...   client-reducer.ts:51减速机链处于等级:10
  client-effects.ts:72效果链处于等级:10

它表示reducer在效果之前首先运行,Effect-Class是一个后拦截器,而不是预拦截器。见流程图: enter image description here