首页 > 其他 > 详细

Effects

时间:2021-04-15 09:23:53      阅读:21      评论:0      收藏:0      [点我收藏+]

一、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

Effects

原文:https://www.cnblogs.com/starof/p/14564570.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!