angular 11 ngrx/effects 使用理解
2021年2月8日 00:05
编程技术
angular 11 ngrx/effects 使用理解
我的理解:这个模块就是把网络请求获取数据,然后更新数据状态的操作合并到了一起。依然需要手动触发,既不会启动时自动加载,也不会获取时只加载一次。
例子:
有一个全局的数据:站点信息
interface AppState {
    site: ISite;
}
通常的方法是:
- 网络请求获取数据
 - 更新到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)