Angular NGRX循环响应数据

Angular NGRX looping response data

// 动作

export class LoadPlayersWinLoseCount implements Action {
  readonly type = PlayersActionTypes.LOAD_PLAYERS_WIN_LOSE_COUNT;

  constructor(public accountId, public queryParams, public payload?: IWinlose, ) {}
}

// 减速器

export function playersWinLoseCount(state = initialStateWinLose, action: PlayersActions): IWinlose {
  switch (action.type) {
    case PlayersActionTypes.LOAD_PLAYERS_WIN_LOSE_COUNT:
      console.log(JSON.stringify(state));
      console.log(action.payload);
      return { ...state, ...action.payload };
    default:
      return state;
  }
}

//效果

 getWinLossCount$: Observable<Action> = createEffect(() =>
  this.actions$.pipe(
    ofType(PlayersAction.PlayersActionTypes.LOAD_PLAYERS_WIN_LOSE_COUNT),
    switchMap(({ accountId, queryParams }) =>
      this.playersService.getWinLoseCount(accountId, queryParams)
        .pipe(
          map((playersWinLoseCount: IWinlose )  =>
            new PlayersAction.LoadPlayersWinLoseCount(accountId, queryParams, playersWinLoseCount)
          ),
          catchError(() =>
            EMPTY
          )
        )
      )
    ),
  );

// 服务

get(endpoint, params?, headers?): Observable<any> {
    return this.httpClient.get<any>(this.BASE_API_URL + endpoint, {
      ...headers,
      ...params
    })
    .pipe(
      catchError(this.errorHandle)
    );
  }



getWinLoseCount(accountId: number, queryParams: IQuery): Observable<IWinlose> {
    return this.generalService.get(`/players/${accountId}/wl`, queryParams);
  }

// 组件

  queryParams;
  playersWinLoseCount$: Observable<IWinlose>;

  constructor(
    private store: Store<{ playersWinLoseCount: IWinlose }>
  ) {
    this.playersWinLoseCount$ = store.select('playersWinLoseCount');
  }

  ngOnInit(): void {
    const accountId = this.activatedRoute.snapshot.paramMap.get('id');
    this.activatedRoute.queryParamMap.subscribe(data => this.queryParams = data);
    this.getWinLossCount(accountId, this.queryParams);
  }

getWinLossCount(accountId, queryParams): any {
    this.store.dispatch(new playersActions.LoadPlayersWinLoseCount(accountId, queryParams));
  }

// HTML

<div *ngIf="playersGeneral$ | async as players" class="player-hero">
  <img class="player-avatar" [src]="players.profile?.avatarfull"/>
...

我阅读了 NGRX 文档,如果我在 THML 中使用 abc$ | async,那么我不需要退订。 但是,现在 console.log() 调试循环直到 api 调用限制。

如果我使用 angular 服务而不是 NGRX,数据响应一旦正确。

谢谢。

这里的问题是效果会监听它自己发出的动作:

PlayersAction.PlayersActionTypes.LOAD_PLAYERS_WIN_LOSE_COUNT

然后

new PlayersAction.LoadPlayersWinLoseCount()

您需要更改此逻辑以避免递归,或者在没有理由发出操作时添加条件,例如,如果商店已经有数据。