【问题标题】:Ngrx store and how to prevent reload of dataNgrx 存储以及如何防止重新加载数据
【发布时间】:2017-06-27 19:55:12
【问题描述】:

目前,我尝试通过 Ngrx 商店学习 Angular。在查看样本后,我想出了以下内容。 (完整源码https://github.com/sebfischer83/Cointo/tree/master/angular/src

我有一个容器组件,其中包含存储并从数据库加载实体。

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './materials-Page.component.html',
  styleUrls: ['./materials-Page.component.css']
})
export class MaterialsPageComponent implements OnInit {
  materials$: Observable<MaterialDto[]>;

  constructor(private _store: Store<fromRoot.AppState>) {
    this.materials$ = _store.select(fromRoot.getMaterialsEntities);
  }

  ngOnInit() {
    this._store.dispatch(new LoadMaterialsAction());
  }

但也许我理解有问题,现在每次更改此组件时,ngOnInit 中的调度都会从服务器重新加载所有数据,因此每次单击此页面时我的商店都会刷新。但它不应该使用商店中已经存在的数据吗?

【问题讨论】:

    标签: angularjs reactive-programming ngrx


    【解决方案1】:

    您可以在副作用上使用 rxjs startWith 运算符。所以是这样的:

    loadMaterials$ = this._actions.ofType(materials.MaterialActionTypes.LOAD)
        .startWith(new LoadMaterialsAction())
        .switchMap(() => this._service.query()
        .map((materials) => { ... })
    

    基本上 startWith 操作符会立即调用副作用。所以你不再需要在你的 ngOnInit 中进行调度。

    作为参考,您可以看到使用相同技术的 ngrx 示例应用程序: https://github.com/ngrx/example-app/blob/master/src/app/effects/collection.ts#L44

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2018-05-14
      • 2017-09-10
      • 2023-03-24
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      相关资源
      最近更新 更多