使用服务从服务器获取数据的 Angular2 md-autocomplete(自动完成)

12

我希望使用angular2/material2的Autocomplete组件从服务器获取数据。(https://material.angular.io/components/component/autocomplete)

ts

  emailCtrl: FormControl;
  filteredEmails: any;

  constructor(
    private companieService: CompanieService,
  ) {
    this.emailCtrl = new FormControl();
    this.filteredEmails = this.emailCtrl.valueChanges
        .startWith(null)
        .map(email => this.filterEmails(email));
  }


  filterEmails(email: string) {
    this.userService.getUsersByEmail(email)
      .subscribe(
        res => {
          return res
        },
        error => {
          console.log(error);
        }
      )
  }

HTML

    <md-input-container>
      <input mdInput placeholder="Email" [mdAutocomplete]="auto" [formControl]="emailCtrl" [(ngModel)]="fetchedUser.profile.email">
    </md-input-container>

    <md-autocomplete #auto="mdAutocomplete">
      <md-option *ngFor="let email of filteredEmails | async" [value]="email">
        {{email}}
      </md-option>
    </md-autocomplete>

服务: userService.getUsersByEmail(email) 正在获取这种类型的数据:

 ['email1@email.com','email2@email.com','email3@email.com']

我没有错误,但自动完成没有结果。 在Chrome的调试器(网络选项卡)中,我看到每次更改输入时数据都被正确地拉取。

有没有办法让它在用户点击输入框时就显示所有可用选项,而不是等待第一个字母被键入? - Kyle Krzeski
3个回答

14

我会给你一个我通常使用的例子:

this.SearchForm.controls['city_id'].valueChanges
  .debounceTime(CONFIG.DEBOUNCE_TIME)
  .subscribe(name => {
    this.domain = [['name', 'ilike', name]];
    this.DataService.getAutoComplete('res.city', this.domain)
      .subscribe(res => {
        return this._filteredCity = res['result']['records']
    })
  })

HTML

<div class="mb-1 ml-1 mt-1" fxFlex="30">
  <md-input-container style="width: 100%">
    <input mdInput placeholder="Kota" (blur)="checkAutoComplete('city_id')" [mdAutocomplete]="city_id" [required]="true" [formControl]="SearchForm.controls['city_id']">
  </md-input-container>
  <md-autocomplete #city_id="mdAutocomplete" [displayWith]="displayFn">
    <md-option *ngFor="let city of _filteredCity" [value]="city">
      <span>{{ city.name }}</span>
    </md-option>
  </md-autocomplete>
  <div *ngIf="SearchForm.controls['city_id'].hasError('required') && SearchForm.controls['city_id'].touched" class="mat-text-warn text-sm">Kolom ini wajib diisi.</div>
</div>

就像那样


有没有办法让它在用户点击输入框时就显示所有可用选项,而不是等待第一个字母被键入? - Kyle Krzeski

3
这是我如何完成的。

.html

       <input formControlName="search" [mdAutocomplete]="auto" type="text" class="form-control">
 <md-autocomplete #auto="mdAutocomplete">
     <md-option *ngFor="let data of filteredData | async" [value]="data.text">
    {{ data.text }}
     </md-option>
 </md-autocomplete>

.ts

 filteredData: Observable<any[]>; // async pipe needs to be an Observable
 myContent: any[] = [];

 this.filteredData = this.myformGroup.get('search').valueChanges
 .debounceTime(400)
 .switchMap(value => {

  // get data from the server. my response is an array [{id:1, text:'hello world'}] as an Observable
  return  this.myApiService.getSearch(value); 

}).map(res => this.myContent = res);

请告诉我这个是否适用于您。

1
搜索在此解决方案中未启用,显示的结果基于先前的搜索关键字... - Sreekumar P
不,这不是之前的代码,因为如果你想在每次按键抬起时发出请求,只需要删除以下代码: let exist = this.myContent.findIndex(t => t.text === value); if (exist > -1) return; - Robin
不要使用 do,而应该使用 switchMap 来处理之前正在进行的请求,并返回 this.myApiService.getSearch()(从这里完全删除 subscribe)。删除延迟 500,因为 switchMap 处理了我们的请求等待。然后添加 subcribe,直接写入 this.filteredData。同时记得在 ngOnDestroy 方法中取消订阅或使用 takeUntil / takeWhile。 - MTJ
@user1740331 是的!我已经按照您提到的使用mergeMap操作符进行了重构。 - Robin
1
@Robin,mergeMap不会停止正在进行的API调用,你的响应以什么随机顺序到达。请参见https://dev59.com/VFkT5IYBdhLWcg3wf_tN#42227335上的示例图。 - MTJ
@user1740331 是的,已经更新了,使用了你提供链接中描述的 switchMap 操作符。 - Robin

0

my.component.html

<form [formGroup]="myForm">
  <mat-form-field>
    <input matInput
        formControlName="email"
        [matAutocomplete]="autoEmailGroup"
        name="email"
        type="email"
        placeholder="Email"
        aria-label="Email" />
    <mat-autocomplete
        autoActiveFirstOption
        #autoEmailGroup="matAutocomplete">
      <mat-option
          *ngFor="let email of emailOptions | async"
          [value]="email">{{ email }}</mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

my.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

import { Observable } from 'rxjs';
import { startWith, tap, switchMap, map, filter } from 'rxjs/operators';
import { empty } from 'rxjs/observable/empty';

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {

  myForm: FormGroup;
  emailOptions: Observable<string[]>;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
  ) { }

  createForm() {
    this.myForm = this.fb.group({
      email: new FormControl(),
    });

    const _fetchEmailsFromServer = (): Observable<string[]> => {
      // TODO you need to ultilize your service here
      return empty();
    };

    this.emailOptions = this.myForm.get('email')!.valueChanges
      .pipe(

        startWith(''),

        switchMap((input: string) => {
          return _fetchEmailsFromServer().pipe(

            // handle your HTTP response here
            map((response: any): string[] => {
              return <string[]> response!.data!.emails;
            }),

            tap((emails: string[]) => {
              // LOGGING
              console.log('Received emails:', emails);
            }),

            // you can filter emails fetched from your server here if you want
          );
        }),

      ).pipe(

        // default value to be displayed before HTTP task is completed
        startWith([]),
      );
  }

}

参考资料:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接