0

I have an observable variable that gets its value from the store. I have a subscribe method on it to listen to updates. In it I try to assign a regular variable one of the values of the observable variable. I console log it to see if it has been updated and it has but the value is not updated in the template.

I have tried listening to the observable in the template and that works fine. I need however to manipulate the returned answer so I can't do it this way.

I have also tried with

this.cdr.detectChanges();

and that works but it feels hacky and overkill for something so simple. Also just in case someone wonders my component does not have

ChangeDetectionStrategy=OnPush

.

This is how the variable is initialised.

this.filters$ = this.store.let(getListsContactsFilters());  

This is what the subscription looks like.

this.filters$.subscribe((filters) => {
   this.selectedAreas = filters.selectedAreas;
});  

I then do this in the template

<div *ngFor="let area of selectedAreas">
  <h1>{{area.title}}</h1>
</div>

I also tried printing out selectedAreas in the template:

{{selectedAreas | json}}

and this stays as an empty array even after the subscribe function is triggered.

Really super simple so god knows why it is not working.

I expect this.selectedAreas to have the value of filters.selectedAreas in the template. Which btw is and array of objects.

2 Answers2

1

I have been through the same problem, the point is that Angular is unable to detect changes outside of its scope (in this case ngRx). I think you can't get it working without that detectChanges statement. It's not overkill, it's how angular works.

Here's a link to my question:

Angular 5 ngOnChanges fires only once in child component

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
  • How come OP's code works fine if you do the subscribe in the template using the async pipe? It's only when you do a manual subscribe as OP describes where it doesn't get updated... – Weblurk May 20 '19 at 07:28
1

Please try

<div *ngFor="let area of (selectedAreas | async)">

It helped me. I used in

this.autoUploadSubscription = this.flow.events$.subscribe(event => {}

<tr *ngFor="let attachment of  (flow.transfers$ | async).transfers"></tr>

trackTransfer(transfer: Transfer) {
  return transfer.id;
}

https://medium.com/angular-in-depth/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794


records$: Observable<any>;

ngOnInit() {
  this.records$ = this.clientService.getAll(1, this.pagesize);
}

<table *ngIf="records$ | async as records">
  <tr *ngFor="let record of records.data">
Maxim
  • 21
  • 3