角形延迟获取变量

时间:2019-11-27 11:42:19

标签: html angular angular-material

我正在为货币下拉列表创建一个角度组件,以便在其他各种组件中使用。

我遇到了一个问题,尽管我将表单的值设置为当前用户的货币(从数据库中获取),这会导致延迟,例如在返回该值之前似乎创建了下拉菜单,这意味着直到单击下拉菜单,该值才变为当前值。

该组件的html如下所示:

<div class="currency-select">
  <mat-form-field>
    <mat-select [formControl]="currencyForm" (openedChange)="selectSearch.focus()" placeholder="Currency:">
      <aemat-select-search (search)="filterCurrencyOptions($event)" #selectSearch (keydown)="$event.stopPropagation()">
      </aemat-select-search>
      <mat-option *ngFor="let currency of filteredCurrencies" [value]="currency.counter_currency_code" (click)="updateCurrency()">
          <flag-icon country="{{ (currency.counter_currency_iso_2 || '').toLowerCase() }}"></flag-icon>  {{currency.counter_currency_code}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</div>

和组件的相关区域如下所示:

@Component({
    selector: 'app-currency-selector',
    templateUrl: './currency-selector.component.html',
    styleUrls: ['./currency-selector.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class CurrencySelectorComponent implements OnInit {
    currencies: Array<CurrencyInterface>;
    filteredCurrencies: Array<CurrencyInterface>;
    currencyForm = new FormControl();
    currentCurrency: string;

ngOnInit() {
        this.getCurrencies()
            .subscribe(data => {
                this.currencies = data;
                this.currencies.push(this.usdOption);
                this.currencies = this._sortRemoveDupes(this.currencies, 'counter_currency_code', 'counter_currency_code');
                this.filteredCurrencies = this.currencies;
            });

        this.getCurrentCurrency()
        .subscribe(data => {
            this.currentCurrency = data[0].currency;
            this.currencyForm.setValue(this.currentCurrency);
        })

    }

getCurrencies(): Observable<Array<CurrencyInterface>> {
        return this.httpClient.get<Array<CurrencyInterface>>(`${this.backendService.url}/currency_rates_view`).pipe(
            catchError(error => {
                this.backendService.handleError(error);
                return of([]);
            })
        ).pipe(shareReplay(1));
    }

getCurrentCurrency(): Observable<Array<UserView>> {
        return this.httpClient.get<Array<UserView>>(`${this.backendService.url}/users_view?id=eq.${this.backendService.userId}`)
        .pipe(
            catchError(error => {
                this.backendService.handleError(error);
                return of([]);
            })
        ).pipe(shareReplay(1));
    }

然后简单地从其他组件中调用该组件:

<app-currency-selector></app-currency-selector>

使用上面的代码,当我加载其他组件时,我可以看到一个带有占位符的下拉菜单,显示“货币:”

当我单击一次时,占位符而不是下拉,而是成为用户数据库货币值的currency_code上方的上标。

然后,我再次单击该下拉列表,然后该下拉列表可以正常工作(尽管由于搜索栏的原因,它仍然存在故障,但这是另一个问题!)

有没有一种方法可以让我在加载其他组件时选择用户的币种,而不必单击下拉菜单以使其出现?

0 个答案:

没有答案