简体   繁体   中英

Bug Child component input to patch reactive form does not update on Oninit

I got data in ngrx entity store that's gets displayed in chunks according to pager, my problem is rxjs some how its remembering the paging for example I get first page data from server it works then if I get the next page it loads it fine now if I go back to first page the data is truncated by switchMap and if I go front one page once more switchMap gives me an empty array when there is data in the store...After this am totally confused from rxjs...

here is the code I also show when creating new array everything works I just don't understand this strange effect why cause of immutable data? also is I use ngrx to load a saved state for an input in a child component on Oninit I patch the form with the saved state then I set a listener on the form so each time input changes I save it. The problem in development it works just fine but in production it fails to patch input am guessing loading the data takes a longer time after Oninit has already ran.

Whats the best way to handle this scenario, tried diffrent metthods some give an error cause data modified before view rendered another gets me in endless loop. Here is child Code

export class ChildComponent implements OnInit {
  @Output() updateFilters = new EventEmitter<string>(false);
  @Input() filters: MessageFilter;

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.form = fb.group({ kind: [] });
  }

  ngOnInit() {
    if (this.filters.kind) {
      this.form.patchValue({kind: this.filters.kind});
    }

    this.form.valueChanges.pipe(
      untilDestroyed(this),
      distinctUntilChanged(),
    ).subscribe(values => {
      this.updateFilters.emit(values.kind);
    });
  }
}

How about using OnChanges instead? Checking the change states / values of your @Input() filters

import { OnChanges, SimpleChanges } from '@angular/core';


@Component({...})
export class ChildComponent implements OnInit, OnChanges {

   ...

   @Input() filters: MessageFilter;

   ngOnChanges({ filters }: SimpleChanges) {
       console.log(filters);     // if you want to check any states/activities
    
       if (filters && filters.currentValue && filters.currentValue.kind)
            this.form.patchValue({ kind: this.filters.kind });   
   }

   ngOnInit() {
       this.form.valueChanges.pipe(
          untilDestroyed(this),
          distinctUntilChanged(),
       ).subscribe(values => this.updateFilters.emit(values.kind));
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM