angular 11 ngrx/effects 使用理解

Fork Me On Github

angular 11 ngrx/effects 使用理解

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

例子:

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

ts
   
interface AppState {
    site: ISite;
}
123

通常的方法是:

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

app-component.ts

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

app.actions.ts

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');
123456

安装

 
npm i @ngrx/effects
1

声明effects

ts
                  
@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,
    ) {
    }
}
123456789101112131415161718

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

声明

app.moudule.ts

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

获取并使用

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

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

还必须请触发

app-component.ts

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

大致流程

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

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