angular 11 ngrx/effects 使用理解

Fork Me On Github

angular 11 ngrx/effects 使用理解

我的理解:这个模块就是把网络请求获取数据,然后更新数据状态的操作合并到了一起。依然需要手动触发,既不会启动时自动加载,也不会获取时只加载一次。

例子:

有一个全局的数据:站点信息

interface AppState {
    site: ISite;
}

通常的方法是:

  1. 网络请求获取数据
  2. 更新到Store中

app-component.ts

ngOnInit() {
    this.service.site().subscribe(site => {
        this.store.dispatch(setSite({site}));
    });
}

app.actions.ts

export const selectSite = createSelector(
    (state: AppState) => state.site
);

export const setSite = createAction('[app]SET_SITE', props<{site: ISite}>());
export const getSite = createAction('[app]GET_SITE');

安装

npm i @ngrx/effects

声明effects

@Injectable()
export class AppEffects {

    loadSite$ = createEffect(() => this.actions$.pipe(
        ofType(getSite),
        switchMap(() => this.service.site().pipe(
            map(site => setSite({site})),
            catchError(() => EMPTY)
        ))
    ));


    constructor(
        private service: ShopService,
        private actions$: Actions,
    ) {
    }
}

请注意 ofType 的参数不能是 setSite 不然或导致无限循环

声明

app.moudule.ts

@NgModule({
  imports: [
    EffectsModule.forRoot([AppEffects]),
  ],
})

获取并使用

this.store.select(selectSite).subscribe(site => {
    // TODO
});

到这里并不能自动发送请求获取到信息

还必须请触发

app-component.ts

ngOnInit() {
    this.store.dispatch(getSite());
}

大致流程

dispatch(getSite()) --> AppEffects.loadSite$ --> service 网络请求 --> setSite({site}) 更新到Store --> 响应 select(selectSite)

Click here to view
Tags: angular
0 775 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式