• 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

    如果觉得本文对您有帮助~可以支付宝(左)或微信支持一下:


    看到小伙伴打赏时给我写一些鼓励的话,真的非常感动,谢谢你们。


    我开了个微信公众号(第三个二维码)用来分享自己的职场英语相关学习经验,感兴趣可以关注,我会不断更新~


    微信打赏微信公众号

  • 相关阅读:
    (转+原)android获取系统时间
    (转+原)VC编译错误:uafxcw.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) 已经在 LIBCMT.lib(new.obj) 中定义
    android的reference table的问题
    (原+转)Eclipse中Android调用OpenCv
    JAVA IO 字符流 FileReader FileWriter
    JAVA IO
    JAVA FIle类
    JAVA 泛型
    JAVA Collection工具类 Collections
    JAVA Map子接口之 HashMap
  • 原文地址:https://www.cnblogs.com/starof/p/14564570.html
Copyright © 2020-2023  润新知