Home > Enterprise >  How do I transfer values from the store to the form?
How do I transfer values from the store to the form?

Time:08-15

I get data from store in this way:

  ngOnInit(): void {
    this.store.pipe(select(getPerson))
    this.store.dispatch(loadPerson());
  }

But I need to be able to transfer data from the store to the form.

Here is an example of how a request is executed without ngrx:

formPerson: FormGroup = this.fb.group({});

this.personService.fetch()
.pipe(
  tap((user) => {
    this.formPerson.get('username')?.setValue(user['username']);
    this.formPerson.get('full_name')?.setValue(user['full_name']);
    this.formPerson.get('email')?.setValue(user['email']);
    this.formPerson.get('phone')?.setValue(user['phone']);
  })
)

CodePudding user response:

If service is returning same property names that angular reactive form has, then you can use the following method.

this.store.pipe(select(getPerson),filter(obj=>obj!=null))
      .subscribe((person) => {
        this.formPerson.patchValue(person);
      })

CodePudding user response:

I usually just add a subscription

person$: Observable<Person>;
personSubscription: Subscription;
formPerson: FormGroup = this.fb.group({});

ngOnInit(): void {
 person$ = this.store.pipe(select(getPerson));
 
 //Subscribe
 personSubscription = this.person$.subscribe(person => {
     if (person) {
       this.formPerson.get('username')?.setValue(user['username']);
       this.formPerson.get('full_name')?.setValue(user['full_name']);
       this.formPerson.get('email')?.setValue(user['email']);
       this.formPerson.get('phone')?.setValue(user['phone']);
     }
 });

 this.store.dispatch(loadPerson());
}

Dont forget to unsubcribe on the destroy

ngOnDestroy(): void {
  this.personSubscription.unsubscribe();
}

}

  • Related