1

I am writing an angular application where one of my components subscribes to lots of values from a ngrx store. My ngOnInit function looks like:

this.store.pipe(select(searchResults), takeUntil(this.destroyed$))
  .subscribe(results => this.searchResults = results);
this.store.pipe(select(searchError), takeUntil(this.destroyed$))
  .subscribe(error => this.searchError = error);
// Lots of similar statements below

I think this is overly verbose. It also makes it difficult to grasp at a glance which fields get their values from the store. My intuition says it should be possible to write this in a more concise way, like in the example below:

this.syncField(searchResults, 'searchResults');
this.syncField(searchError, 'searchError');
// Lots of similar statements below

This approach relies on a syncField method, which I have been unable to write. I tried the following:

syncField<T>(selector: MemoizedSelector<object, T>, field: keyof MyComponent) {
    this.store.pipe(select(selector), takeUntil(this.destroyed$)).subscribe(value => {
        this[field] = value;
    });
}

However, the component has some read-only fields, which causes the assignment (this[field] = value) to fail with the message: Cannot assign to [readonly field name] because it is a constant or a read-only property..

This gives raise to the questions:

  1. Is it possible to use keyof T in such a way that it filters out read-only properties?
  2. If this is impossible, is there another way we could write the syncField method?
  3. Alternatively, is there a best practice to make subscribing to lots of observables less verbose?
aochagavia
  • 5,887
  • 5
  • 34
  • 53

0 Answers0