【问题标题】:Angular ngrx: Access to an adjacent slice of storeAngular ngrx:访问相邻的商店切片
【发布时间】:2021-02-28 22:50:41
【问题描述】:

当我的组件初始化时,我想调度一个动作来创建“campaignDraft”对象。 如果“CampaignOverview”存在,我需要将“campaignDraft”设为相同,如果不存在,将其设为预设对象 {a: 1} 例如

问题是我正在尝试使用 Effects 来实现这一点,但我的所有操作都会导致浏览器死机。

// component.ts
   ngOnInit(): void {
    this.store.dispatch(getCampaignDraft());
    this.campaignFormSubscription = this.store
          .pipe(select(selectCampaignDraft))
          .subscribe((campaignDraft: CampaignModel) => {
            this.campaignForm.patchValue(campaignDraft, { emitEvent: false });
       });
    }
          
 // actions
  export const getCampaignDraft = createAction(CampaignDraftActionTypes.GET_CAMPAIGN_DRAFT);
     
 // effects
     getCampaignDraft$ = createEffect(() => {
        return this.actions$.pipe(
          ofType(fromCampaignDraftActions.getCampaignDraft),
          switchMap((action) => withLatestFrom(this.store.pipe(select(selectCampaignOnly)))),
          map((campaign) => fromCampaignDraftActions.createCampaignDraft({ campaign: {a: 1} })) 
        );
    });

// reducer
  on(campaignDraftActions.createCampaignDraft, (state, { campaign }) => {
    return {
      ...campaign,
    };
  }),

我不知道如何检查 Store 是否有效 - “campaignOverview”是否存在以使用此对象或预设的对象调度另一个操作,请帮助。

【问题讨论】:

    标签: angular ngrx ngrx-store ngrx-effects


    【解决方案1】:

    我们可以使用 withLatestFrom 作为运算符,而不是使用 switchmap 返回它,如下所示

      getCampaignDraft$ = createEffect(() => {
        return this.actions$.pipe(
          ofType(fromCampaignDraftActions.getCampaignDraft),
          withLatestFrom(this.store.pipe(select(selectCampaignOnly))),
          map(([action, campaign]: [ActionType, CampaginStateSliceType]) => {
            if (exists) {
              return A_Action();
            } else {
              return B_Action();
            }
          })
        );
      })
    

    【讨论】:

    • 非常感谢!那是!你能告诉我如何检查2个商店切片吗?如果第一个存在 - 返回它,如果不存在 - 返回第二个然后调度​​结果操作。
    • 你可以根据需要在 withLatestFrom 中添加任意数量的 observables withLatestFrom(this.store.pipe(select(selectCampaignOnly)), this.store.pipe(select(secondSelector))), map(([行动,活动,秒状态]:[ActionType,CampaginStateSliceType,SecondStateSliceTYpe])=> {
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2018-03-23
    • 1970-01-01
    • 2019-01-24
    • 2021-01-20
    • 1970-01-01
    • 2022-10-21
    相关资源
    最近更新 更多