Home > Mobile >  How to extract data from Observable?
How to extract data from Observable?

Time:12-20

How can extract the data to pass it to the form?

user$!: Observable<UserI>

ngOnInit(): void {
  this.user$ = this.userService.getPerson();
  this.initializeForm();
}

initializeForm(): void {
  this.form = this.fb.group({
    fullName: new FormControl(?, Validators.required),
  });
}

CodePudding user response:

You have multiple options:

You could initialize the form when the data is loaded or you could initialize the form with empty/default values and set update the values when the data is loaded.

Method 1:

ngOnInit(): void {
  this.userService.getPerson().pipe(
      tap(user => this.initializeForm(user))
  ).subscribe();
}

initializeForm(user: UserI): void {
  this.form = this.fb.group({
    fullName: new FormControl(user.fullName, Validators.required),
  });
}

Method 2:

ngOnInit(): void {
  this.initializeForm();
  this.userService.getPerson().pipe(
      tap(user => {
          this.form.get('fullName').setValue(user.FullName);
      })
  ).subscribe();
}

initializeForm(): void {
  this.form = this.fb.group({
    fullName: new FormControl('', Validators.required),
  });
}

Personally I prefer to create fields for my controls:

readonly fullName = new FormControl('', Validators.required);

ngOnInit(): void {
  this.initializeForm();
  this.userService.getPerson().pipe(
      tap(user => {
          this.fullName.setValue(user.FullName);
      })
  ).subscribe();
}

initializeForm(): void {
  this.form = this.fb.group({
    fullName: this.fullName,
  });
}

Then I can access them directly, including in html

<input [formControl]="fullName"/>
<span *ngIf="fullName.errors?.required">Fullname is required</span>
  • Related