我在我的 Angular 4 项目中使用 Angular Material 2 Autocomplete。在这个 example 中,我如何实现自动完成值从 HTTP 调用加载? ?
谁能给我一个 Plunker 演示?谢谢
最佳答案
首先,您应该尝试解决您的问题,但幸运的是我很无聊,会提供答案;)
在此示例中,我使用的是:https://jsonplaceholder.typicode.com/users
我们将该 JSON 结果存储为 users
中的可观察对象。然后我们有了可观察的 filteredUsers
,它将显示在模板中。由于这是一个 http 请求,我们希望使用您选择的 distinctUntilChanged
和 debounceTime
来限制 http 请求。在本例中,我们用来捕获用户输入值的表单控件是 searchCtrl
。在监听 valueChanges
时,我们使用 switchMap
来展平结果。
因此,根据以上评论,您的代码将如下所示:
更新(rxjs 6)
this.filteredUsers = this.searchCtrl.valueChanges.pipe(
startWith(null),
debounceTime(200),
distinctUntilChanged(),
switchMap(val => {
return this.filter(val || '')
})
)
}
filter(val: string) {
return this.users.pipe(
map(response => response.filter(option => {
return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
}))
)
}
对于模板,我们使用async
管道:
<mat-form-field>
<input matInput [matAutocomplete]="auto" [formControl]="searchCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let user of filteredUsers | async"
[value]="user.name">
<span>{{ user.name }}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
旧:
this.filteredUsers = this.searchCtrl.valueChanges
.startWith(null)
.debounceTime(200)
.distinctUntilChanged()
.switchMap(val => {
return this.filter(val || '')
})
filter(val: string) {
return this.users
.map(response => response.filter(option => {
return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
}));
}
关于angular - 如何使用 AJAX 实现 Angular Material 2 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47088363/