物料自动填充加载数据的值随着http调用而改变

By simon at 2018-02-07 • 0人收藏 • 19人看过

在我的角度4应用程序,我有一些材料自动完成里面 FormGroup,我只想搜索(做一个HTTP调用)只有wh用户写入 在自动填充字段中的东西。所以我正在关注这个例子: [stackblitz](https://stackblitz.com/edit/auto完整的动力选择,测试 - csip5w?文件=应用%2Fapp.component.ts) 但在我的情况下,我需要做一个远程调用来检索信息,所以我必须 致电服务: * * Service.ts

  getCustomers(name: string) {


    return this.endPointUrlService.checkIfMapIsReady(this.entityLink[2])
      .flatMap((res) => {
        return this.http.get(this.endPointUrlService.cutLinks
          (this.endPointUrlService.mapNames.get('customersSearchMap').get('autocompleteWithWallet')), { params })
          .map((response) => <Customer[]>response);
      })
  }
正如你所看到的,我的服务返回一个Customer[]的可观察值 所以我怎样才能使它在组件中工作?或者更一般地说,我可以做什么 通话价值变化?

1 个回复 | 最后更新于 2018-02-07
2018-02-07   #1

零件:

import { FormControl } from '@angular/forms';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

customerControl = new FormControl();
matchingCustomers = new BehaviorSubject<string[]>([]);

ngOnInit() {
  this.customerControl.valueChanges.subscribe(val => {
    this.customerService.getCustomers(val).subscribe(customers => {

      this.matchingCustomers.next(customers);

      // OR (depends on where you want do filtering [component|service|server]):

      // this.matchingCustomers.next(customers.filter(customer => {
      //   return customer.toLowerCase().indexOf(val.toLowerCase()) > -1;
      // }));

    });
  });
}
模板:
<mat-form-field>
    <input matInput [matAutocomplete]="auto" [formControl]="customerControl">
    <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let customer of matchingCustomers | async" [value]="customer">
            {{ customer }}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>
服务中,我会做一些检查,以防止多余的HTTP调用。像这样的东西:
// optimizations possible

private lastSearchQuery: string = '';
private cachedCustomers: Customer[] = [];

getCustomers(name: string): Observable<Customer[]> {
  if (name.length > 2) { // developer defined value to prevent large responses
    // first search || 'name' is not part of 'lastSearchQuery'
    if (this.lastSearchQuery == ''
      || this.lastSearchQuery.toLowerCase().indexOf(name.toLowerCase()) === -1) {
      this.lastSearchQuery = name;
      return this.http.get<Customer[]>('https://example.org/customers?q=' + name).map(customers => {
        this.cachedCustomers = customers; 
        return customers;
      });
    } else { return Observable.of(this.cachedCustomers); }
  } else { return Observable.of([]); }
}

登录后方可回帖

Loading...