Effects

一、Effects概念

有些Action改变的是外部状态,比如发送HTTP请求,DOM更改。

 

 把Action看成流的话,跟UI相关的数据处理是Reducer,和UI相关的状态之外的叫Effects。

 一个系统就分为Action和Reducer,一个Action出来后可能会改变数据的状态,也可能带来外部的影响,这些外部影响处理完之后可能又会发出一个新的Action。

可以循环往复,任意拼接。

二、代码

 1,新建AppEffectsModule

@NgModule({
    imports: [EffectsModule.forRoot([QuoteEffects])],
})
export class AppEffectsModule { }

2,把AppEffectsModule导入CoreModule

3,写quote.effects

Effects可用用service的模板来建,因为它可以注入。

在effects的构造函数中注入action$流。

写第一个effects处理Load action:

监听action流,捕获到action,把service调用起来,成功的时候发射加载成功的action,失败的时候发射加载失败的action。

quote$ = createEffect(() => {
        return this.actions$.pipe(
            ofType(actions.LOAD),
            switchMap(_ => {
                return this.quoteService.getQuote().pipe(
                    map(quote => new actions.LoadSuccess(quote)),
                    catchError(error => of({ type: actions.LOAD_FAIL, payload: JSON.stringify(error) }))
                )
            })
        )
    });

ofType捕获,筛选什么样的action。

The Effect decorator (@Effect) is deprecated in favor for the createEffect method. See the docs for more info https://ngrx.io/guide/migration/v11#the-effect-decorator

 4,在login中调用

之前quoteService$就不需要了。

this.quoteService$.getQuote().subscribe(quote => {
  this.store$.dispatch({ type: actions.LOAD_SUCCESS, payload: 
  quote })
})

增加一个,发出第一个LOAD action即可。

this.store$.dispatch({ type: actions.LOAD })

 

做到,把程序逻辑从组件中剥离出来。组件只需要在恰当的时间发送action即可。

 

2021-03-22

posted @ 2021-04-15 08:09  starof  阅读(737)  评论(0编辑  收藏  举报