首页 > 解决方案 > 使用异步源的角度选择 - 默认值

问题描述

我有很多<select>绑定到 HTTP 服务(从底层 REST API 获取数据)。我试图尊重 Angular 中的反应模式,这是代码:

<select class="custom-select" formControlName="bankAccountId" >
  <option *ngFor="let x of bankAccounts$ | async" [value]="x.id" >{{ x.name }}</option>
</select>

这导致用户必须手动选择选项的空白选择。我想在 select 中预先选择第一个值(在大多数情况下,用户会手动选择值)。我知道如何使用命令式模式来实现这一点。

ngOnInit() {
  this.bankAccounts$ = this.httpService.getBankAccounts();

  this.bankAccounts$.subscribe(data => {
    this.form.patchValue({ bankAccountId: data[0].id });
  });
}

有什么方法可以在不需要手动订阅 Observable 的情况下实现这一点?谢谢!

标签: angulartypescriptrxjsangular-observable

解决方案


使用水龙头运算符。这样我们就不必手动订阅。

尝试这个:

this.bankAccounts$ = this.httpService.getBankAccounts().pipe(tap(data=> this.form.patchValue({ bankAccountId: data[0].id });));

推荐阅读