处理组件中成功的操作调度

Bre*_*ett 5 ngrx angular

我有一个带有表单的组件,可以将项目添加到列表中。成功将项目添加到列表后,我想使用form.resetForm();,但我无法找到一种简单的方法来知道该操作何时成功。我希望我可以订阅行动调度,但一直没能弄清楚。

我尝试了在网上找到的几种方法,但它们似乎都已经过时了。我确实通过向我的商店添加一个属性并订阅它来使其工作saving,但这对于本应非常简单的事情来说似乎是过多的工作。

有没有办法只订阅我的组件或容器内的内容而不重构我的 NGRX 逻辑?

以下是我的容器中将项目添加到列表中的代码:

addPosition(position: Position) {
  this.store.dispatch(new fromStore.CreatePosition(position));
}
Run Code Online (Sandbox Code Playgroud)

行动:

export const CREATE_POSITION = '[Profile] Create Position';
export const CREATE_POSITION_FAIL = '[Profile] Create Position Fail';
export const CREATE_POSITION_SUCCESS = '[Profile] Create Position Success';

export class CreatePositionSuccess implements Action {
  readonly type = CREATE_POSITION_SUCCESS;
  constructor(public payload: any) {}
}
Run Code Online (Sandbox Code Playgroud)

影响:

@Effect()
    createPosition$ = this.actions$.pipe(
        ofType(positionsActions.CREATE_POSITION),
        map((action: positionsActions.CreatePosition) => action.payload),
        switchMap(position => {
            return this.positionService
                .addPosition(position)
                .pipe(
                    map(newPosition => new positionsActions.CreatePositionSuccess(newPosition)),
                    catchError(error => of(new positionsActions.CreatePositionFail(error)))
                );
        })
    );
Run Code Online (Sandbox Code Playgroud)

我使用的是 ngrx 7 版和 rxjs 6.3 版。

env*_*oiz 5

您可以将Action服务注入组件中,然后订阅它,以便在分派“ CreatePositionSuccess ”操作时进行侦听。

例如,在您的组件中:

import { Actions } from '@ngrx/effects';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

export class SampleClass implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();

  //Injecting the service
  constructor(private actions$: Action){}

  onInit() {
    this.actions$
    .pipe(
      ofType<CreatePositionSuccess>(CREATE_POSITION_SUCCESS),
      // You can add more operator if it is necessary into the observable.
      takeUntil(this.unsubscribe$)
    )
    .subscribe(() => {
      // Here you can execute the reset function
    });
  }

  onDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,您将能够在调用成功操作后立即重置表单。

顺便说一句,“取消订阅”Subject 用于在组件被销毁时自动取消订阅 Observable,以避免内存泄漏。您可以注意到我如何将它用于 on destroy 方法。