我有一个静态的数据集,一个国家列表,在一些组件上使用。此数据加载到这些组件的ngOnInit()上,但我只想在第一次请求数据时加载它们(存储为空)。以后每次加载组件时,我只想使用存储区中的数据,而不想“刷新”它。
如何使用ngrx实现这一点?
我在用特效。我的代码是这样的:
组成部分:

export class EditPageComponent implements OnInit {
countries$: Observable<Country[]>

constructor(private store: Store<fromContacts.State>) {
    this.countries$ = store.select(fromContacts.getCountriesEntities);
}
ngOnInit() {
   this.store.dispatch(new countries.Load());
}

效果:
    @Effect()
      loadCollection$: Observable<Action> = this.actions$
        .ofType(countries.LOAD)
        .switchMap(() =>
          this.countriesService
        .getCountries()
        .map((countriesList: Country[]) => {
          return new countries.LoadSuccess(countriesList);
        })
        .catch(error => of(new countries.LoadFail(error)))
  );

减速器:
case countries.LOAD_SUCCESS: {

      const countriesList: Country[] = action.payload;
      const reducedCountries: { [id: string]: Country } = countriesList.reduce((countrs: { [id: string]: Country }, countr: Country) => {
        return Object.assign(countrs, {
            [countr.code]: countr
        });
    }, {});

谢谢,
嘎布

最佳答案

有不同的方法可以做到这一点。首先,可以使hasLoaded: boolean属性保持de状态。然后你可以在打电话之前检查一下。

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

另一个选项是让@effect检查hasloaded属性:
@Effect()
  loadCollection$: Observable<Action> = 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)))
);

为此,您需要在effects构造函数中提供存储。

关于angular - ngrx仅在存储为空时才从服务器加载数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46705366/

10-10 00:20
查看更多