angular - 远程自动完成查询
问题描述
我是 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:
。我究竟做错了什么?谢谢!
解决方案
就像我写的那样,您的问题出在您使用的异步管道中
let terminal of (filteredTerminals | async)?.results
当然,它是因为过滤的终端是不可观察的或承诺的。
推荐阅读
- python - 如何使用 curses stdscr.getch() 在 MacOS 上的 Jupyter Notebook 中捕获按键?
- vba - 带有嵌入变量的 VBA 字符串
- c# - 如何使用 FileHelper 库获取分隔符的数量
- python - 如何使用不同参数模型的网格搜索和交叉验证?
- snowflake-cloud-data-platform - 如果复制文件时 S3 前缀不正确,如何接收错误?
- reactjs - 有没有函数的didmount方法?
- python-3.7 - 无法在 anaconda propmt windows 10 中的 python-3.7.0 版本中安装 xgboost
- gradle - gradle 6.x kotlin spring-boot jar 发布失败,需要 gradle-kotlin-dsl 中的解决方法
- c# - 除非使用异步,否则 Ok() 在当前上下文中不存在
- applescript - 如何在当前 Keynote 文档的当前幻灯片上选择一个特定图像?