angular - 如何从 Observable 中提取数据?

标签 angular

如何提取数据并将其传递到表单?

user$!: Observable<UserI>

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

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

最佳答案

您有多种选择:

您可以在加载数据时初始化表单,也可以使用空/默认值初始化表单并在加载数据时设置更新值。

方法一:

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),
  });
}

方法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),
  });
}

我个人更喜欢为我的控件创建字段:

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,
  });
}

然后我可以直接访问它们,包括在 html 中

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

关于angular - 如何从 Observable 中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70420001/

相关文章:

javascript - 通过窗口访问 Angular2 应用程序丢失了 "this"的范围

Angular 表单模块禁用以前工作的表单

angular - 如何使用 Reactive 表单设置单选按钮值?

angular - 什么相当于 Angular 6 中的 AngularJS ngcookies?

dictionary - 未调用 http 响应上的 RxJs/Angular2 映射函数

javascript - Angular 5 错误 :Can't bind to 'ngForFor' since it isn't a known property of 'li'

angularjs - 找不到 namespace Angular

angular - 如何有条件地添加 mat-raised-button?

javascript - Angular 2 快速入门 : unexpected token <

angular - *ngFor 的哪种方法更好 : ng-container or pipe slice?