ngrx Load data from server only if the store is empty

前端 未结 4 1309
离开以前
离开以前 2021-01-01 15:19

I have a static set of data, a list of countries, that are used on some components. This data is loaded upon the ngOnInit() of these components but I\'d like to

4条回答
  •  轮回少年
    2021-01-01 15:58

    TL;DR

    Use take(1) operator in the effect

    Don't forget the error handling using catchError and return EMPTY, otherwise when an error occurs, that error will be returned always (timeout, auth error, offline...)


    I had exactly the same case as you, what I did was adding in the effects the rxjs operator take to fetch the countries only the first time the LoadCountries action was dispatched.

    @Effect()
      loadCountries$: Observable = this.actions$.pipe(
        ofType(CoreActionTypes.LoadCountries),
        mergeMap(() =>
          this.countriesService.getAllCountries().pipe(
            map(c => new LoadCountriesSuccess(c)),
            catchError(() => {
              this.store.dispatch(new LoadCountriesFailed());
              return EMPTY;
            })
          )
        ),
        take(1)
      );
    

    Returning EMPTY inside catchError will complete the observable without passing through the take(1)

提交回复
热议问题