ngrx Load data from server only if the store is empty

前端 未结 4 1308
离开以前
离开以前 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:40

    There are different ways of doing this. First of all you can keep a hasLoaded: boolean property in the state. Then you can check this before you make the service get call.

    ngOnInit() {
      this.store.select(getHasLoaded)
        .take(1)
        .subscribe(hasLoaded => {
          if (!hasLoaded) this.store.dispatch(new countries.Load()); 
        }
    }
    

    Another option is to let your @Effect check the hasLoaded property:

    @Effect()
      loadCollection$: Observable = this.actions$
        .ofType(countries.LOAD)
        .withLatestFrom(this.store.select(getHasLoaded)
        .filter(([ action, hasLoaded ]) => !hasLoaded) // only continue if hasLoaded is false 
        .switchMap(() =>
          this.countriesService
            .getCountries()
            .map((countriesList: Country[]) => {
              return new countries.LoadSuccess(countriesList);
            })
        .catch(error => of(new countries.LoadFail(error)))
    );
    

    For this to work you need to provide the store in your Effects constructor.

提交回复
热议问题