NgRx 效应导致无限 http 循环

NgRx Effect results in infinite http loop

我的效果如下:

  initCompaniesAndSetCompanyEffect$: Observable<Action> = createEffect(
    (): Observable<Action> =>
      this.actions$.pipe(
        ofType<changeCompanyActions.InitCompaniesAction>(changeCompanyActions.SelectedCompanyActionTypes.INIT_COMPANY),
        mergeMap(() =>
          this.companyService
            .getCompanies()
            .pipe(
              mergeMap((companies) => [new changeCompanyActions.LoadCompaniesAction(companies), new changeCompanyActions.InitSetCompanyAction(companies[0])])
            )
        )
      )
  );

我的行为:

export class InitCompaniesAction implements Action {
  readonly type = SelectedCompanyActionTypes.INIT_COMPANY;
}
export class LoadCompaniesAction implements Action {
  readonly type = SelectedCompanyActionTypes.LOAD_COMPANIES;
  constructor(public payload: Company[]) {}
}

export class InitSetCompanyAction implements Action {
  readonly type = SelectedCompanyActionTypes.INIT_COMPANY;
  constructor(public payload: Company) {}
}

最后在我的组件中调度 onInit 时:

  companies$: Observable<Company[]>;
  selectedCompany$: Observable<Company>;

  constructor(private store: Store<CompanyStoreState.SelectedCompanyState>) {}

  ngOnInit(): void {
    this.companies$ = this.store.select(CompanyStoreSelectors.selectCompaniesList);
    this.selectedCompany$ = this.store.select(CompanyStoreSelectors.selectSelectedCompany);
    this.store.dispatch(new CompanyStoreActions.InitCompaniesAction());
  }

但这会导致服务进行无限次 http 调用,环顾四周时,我看不出我所做的与我找到的解决方案有何不同。 谁能帮忙?

你的InitSetCompanyActionInitCompaniesAction的类型相同SelectedCompanyActionTypes.INIT_COMPANY

所以当效果触发时,它会循环回来,因为您分派的动作具有相同的类型,所以 ofType 会选择那个。