Angular 2 Asynchronous pipe does not display new values ​​with Observable

I am using the NgRx Store in my application.

home.html

<list-objects
      [array]="array| async"
      (Edit)="Edit($event)"
      (Delete)="Delete($event)"
 ></list-objects>

Home.ts

export class HomePage {
     public array: Observable<itm[]>;

     constructor(){
          this.array= this.store.select(state => state.array);

          this.array.subscribe((a) => {
             console.log(a); //VALUES OK
          }
      }

      Edit(event){
          this.store.dispatch(this.actions.updateItem(event.item));
      }
  }

When I edit an array element, the asynchronous channel does not update the view, but the values ​​in the "array" objects are correct (console.log inside the subscription shows the updated value). When I click somewhere in the DOM (open the modal, press the buttons ...), I look for updates with new values.

I also register a child component of "ngOnChanges" and it does not start with the new value.

+4
source share
3 answers

Try something like this:

( , ).

<list-objects
      [array]="array"
      (Edit)="Edit($event)"
      (Delete)="Delete($event)"
 ></list-objects>

export class HomePage {
     public array: itm[];

     constructor( private zone:NgZone ){
        this.store.select(state => state.array).subscribe((a) => {
              this.zone.run(() => {
                   this.array = a;
              });
          }
      }

      Edit(event){
          this.store.dispatch(this.actions.updateItem(event.item));
      }
  }

. this.zone.run, , .

, . Http, . , Angular , .

0

Try:

constructor(private changeDetector: ChangeDetectorRef) {
              this.array= this.store.select(state => state.array);

              this.array.subscribe((a) => {
                 console.log(a); //VALUES OK
                 this.changeDetector.markForCheck();
              }
          }
0

ngrx ( ), . , : (, ..), HTTP, (setTimeout setInterval).

:

  • Turn on changeDetection: ChangeDetectionStrategy.OnPushand then update your mailbox with a subscription, in which case you will need to call markForCheck():

    import { ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
    
    
    @Component({
        ...,
        changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class HomePage {
        public array: itm[];
        constructor(private ref: ChangeDetectorRef) {
            this.store.select(state => state.array).subscribe(a => {
                this.arr = a;
                this.ref.markForCheck();
            });
        }
    }
    
  • The second way is to enter ChangeDetectorRefand call detectChanges()in the subscription. But do not do it. And do not use for this NgZone.

ngrx + ChangeDetectionStrategy.OnPush A good way to improve change detection performance.

0
source

Source: https://habr.com/ru/post/1652593/


All Articles