Sebastian
Sebastian

Reputation: 972

Ngrx store and how to prevent reload of data

currently, I try to learn Angular with Ngrx store. After looking at the samples I came up with the following. (for the complete source https://github.com/sebfischer83/Cointo/tree/master/angular/src)

I have a container component that contains the store and load the entities from the database.

@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());
  }

But maybe I have a problem with understanding, now every time I change to this component the dispatch in the ngOnInit will reload all data from the server, so my store will refresh every time I click on this page. But shouldn't it use the data already present in the store?

Upvotes: 1

Views: 2043

Answers (1)

seescode
seescode

Reputation: 2131

You can use the rxjs startWith operator on your side effect. So something like this:

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

Basically the startWith operator will immediately invoke the side effect. So you would no longer need to do a dispatch in your ngOnInit.

For reference you can see the ngrx example app doing this same technique: https://github.com/ngrx/example-app/blob/master/src/app/effects/collection.ts#L44

Upvotes: 3

Related Questions