首页 > 解决方案 > 远程自动完成查询

问题描述

我是 Angular 的新手,并尝试制作一个在后端过滤内容的自动完成表单。我有终端的类和接口:

export class Terminal {
  constructor(
      public id: number,
      public name: string,
      public city: string,
      public country: string) {}
}


export interface ITermianlResponse {
  results: Terminal[];

然后我有一个服务:

@Injectable()
export class Service {

  constructor(private http: HttpClient) {}

  search(value): Observable<ITermianlResponse> {
    return this.http.get<ITermianlResponse>('http://127.0.0.1:8000/api/v1/public/terminal_ac/?q=' + value)
    .pipe(
      tap((response: ITermianlResponse) => {
        response.results = response.results
          .map(terminal => new Terminal(terminal.id, terminal.name, terminal.city, terminal.country))
        return response;
      })
  );

  }
}

后端收到我的请求并给出答复,至于单:

{"results": [{"id": "1", "name": "Shanghai Terminal", "city": "Shanghai", "country": "China"}], "pagination": {"more": false}}

我的组件如下:

export class SearchComponent implements OnInit {
  filteredTerminals: ITermianlResponse;
  terminalsForm: FormGroup;

  constructor(private fb: FormBuilder, private Service: Service) {}

  ngOnInit() {
    this.terminalsForm = this.fb.group({
      terminalInput: null
    })

    this.terminalsForm.get('terminalInput').valueChanges
    .pipe(
        debounceTime(300),
        switchMap(value => this.Service.search(value)),
    ).subscribe(result => this.filteredTerminals = result);
  }


  displayFn(terminal: Terminal) {
    if (terminal) { return terminal.name; }
  }

}

最后是我的html:

<form class="example-form" [formGroup]='terminalsForm'>
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Choose a terminal" [matAutocomplete]="auto" formControlName='terminalInput'>
  </mat-form-field>
  <span>Your choice is: {{terminalsForm.get('terminalInput').value | json}}</span>

  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let terminal of (filteredTerminals | async)?.results" [value]="terminal">
        <span>{{ terminal.name }}</span>
        <small> | ID: {{terminal.id}}</small>
      </mat-option>
  </mat-autocomplete>
</form>

正如我所说,后端收到我的请求,但浏览器控制台 raise 和 error SearchComponent.html:9 ERROR Error: InvalidPipeArgument:。我究竟做错了什么?谢谢!

标签: angularrxjs

解决方案


就像我写的那样,您的问题出在您使用的异步管道中

let terminal of (filteredTerminals | async)?.results

当然,它是因为过滤的终端是不可观察的或承诺的。


推荐阅读