远程自动完成查询

时间:2019-01-23 06:28:09

标签: angular rxjs

我是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;
      })
  );

  }
}

后端,我收到了我的请求并给出了答案,就像Shan一样:

{"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>

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

1 个答案:

答案 0 :(得分:1)

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

let terminal of (filteredTerminals | async)?.results

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

相关问题