首页 > 解决方案 > ngrx 效果 - 每隔几秒有条件地调用/停止效果的问题

问题描述

我正在尽我所能使用计时器以以下方式每 2 秒有条件地调用我的ngrx 效果:

  @Effect()
  loadSummary$ = this.actions$
  .pipe(
    
    ofType(SummaryTypes.SAVE_SUMMARY),
    
    switchMap((action:any) => (action.running ? timer(0, 2000) : NEVER)),
    
    switchMap((action: any) => {

      console.log(action); /* prints 0 (how is this possible?!) */

      return this.analyticsService.getData(action.fetchArr, action.startAndEndDate).pipe(
        catchError((err) => {
          /* log error */
        }),
      )
    }),
  ) 

所以我每 2 秒后调用第二个 switchMap。action.running在第一次 switchMap 调用中也正确返回 true 或 false,但是,console.log(action)返回 0 和类似地action.fetchArr返回action.startAndDateundefined。

这是因为我无法按action原样返回第一个动作到第二个动作。有人可以指导我做错什么吗?

我想要的是:

我希望我的效果每 2 秒调用一次,如果action.running返回 false 那么它必须立即停止。应该在第二个而不是 0console.log(action);中正确返回传递的对象。switchMap

我尝试了什么:

尝试阅读过去几个小时的效果,甚至尝试使用takeUntil但无法找到任何特定方式。

标签: angularngrxngrx-effects

解决方案


嗨,我尝试了这样的事情并且工作了

  public someSubject = new Subject<boolean>();
  public someObes = from([1, 2, 3, 4]);

  ngOnInit() {
    this.someSubject
      .pipe(
        switchMap(
          (value: boolean): any =>
            timer(0, 200).pipe(
              filter(() => value),
              switchMap((): any => this.someObes)
            )
        )
      )
      .subscribe(value => console.log(value));

    this.someSubject.next(true);

    setTimeout(() => this.someSubject.next(false), 3 * 1000);

    setTimeout(() => this.someSubject.next(true), 5 * 1000);

    setTimeout(() => this.someSubject.next(false), 8 * 1000);
  }
}

pipe我认为你应该timer(0, 2000)


推荐阅读