0
ngOnInit(): void {
    this.filteredAccountOptions = this.accountControl.valueChanges
    .pipe(
      startWith(''),
      map(value => this.accountFilter(value))
    );
    .
    .
    .

实际上,“return this.createDialogService.accountOptions”语句是在“accountSearch(value)”方法中的上一行完成订阅部分之前执行的。这就是为什么显示之前的数据。

private accountFilter(value: string): string[] {
    this.accountSearch(value);
    return this.createDialogService.accountOptions
  }
accountSearch(searchedValue: string) {
    this.createDialogService.searchAccount(searchedValue).subscribe(
      (success) => {
        this.createDialogService.accountOptions = JSON.parse(success.message)
      },
      (error) => {}
    )
  }

我的 HTML

<input type="text" matInput [formControl]="accountControl" [matAutocomplete]="auto1">
    <mat-autocomplete #auto1="matAutocomplete">
        <mat-option *ngFor="let option of filteredAccountOptions | async" [value]="option.Name">
             {{option.Name}}
        </mat-option>
    </mat-autocomplete>
4

1 回答 1

0

因为您在返回 Observable 后更改数据,所以使用swithMap运算符。为避免服务器超载,请使用debounceTime.

  ngOnInit(): void {
    this.filteredAccountOptions = this.accountControl.valueChanges.pipe(
      startWith(''),
      debounceTime(3000),
      switchMap(value => this._accountFilter(value)),
    );
  }

  private _accountSearch(searchedValue: string): Observable<any> {
    return this.createDialogService.searchAccount(searchedValue).pipe(
      map(success =>  JSON.parse(success.message)),
    );
  }
于 2020-05-18T20:33:56.060 回答