我正在尝试在Angular中实现自动完成功能。我从以下服务获取数据(返回具有自动完成值的字符串数组):
this.apiService.getAutoComplete(query).subscribe((data) => {
return data;
})
我是Angular的新手,所以我走错了路。但是我找到了这些样本,看起来很符合我的需求: https://valor-software.com/ngx-bootstrap/#/typeahead
我的问题是样本是基于静态数组的,我现在尝试了一段时间以将其更改为异步数据。但是没有运气。我尝试去异步示例并在功能更改后进行了更改,但没有成功:
getStatesAsObservable(token: string): Observable<any> {
return of(
this.apiService.getAutoComplete('ja').subscribe((data) => {
return data;
})
);
}
HTML:
<pre class="card card-block card-header">Model: {{asyncSelected | json}}</pre>
<input [(ngModel)]="asyncSelected"
[typeaheadAsync]="true"
[typeahead]="dataSource"
(typeaheadLoading)="changeTypeaheadLoading($event)"
(typeaheadOnSelect)="typeaheadOnSelect($event)"
[typeaheadOptionsLimit]="7"
placeholder="Locations loaded with timeout"
class="form-control">
<div *ngIf="typeaheadLoading">Loading</div>
但是,老实说,我不知道在链中的什么地方更改代码,如果我使用的是正确的示例(自动完成不是基于修订数组)。欢迎所有输入。
答案 0 :(得分:1)
您可以使用具有自动完成组件的@ngez库: https://ngez-platform.firebaseapp.com/#/core/autocomplete
component.html
<input type="text" [ngezAutocomplete]="ngezAutocomplete">
<ngez-autocomplete #ngezAutocomplete>
<ngez-autocomplete-option [value]="value" *ngFor="let value of data">
{{value}}
</ngez-autocomplete-option>
</ngez-autocomplete>
component.ts
import { Component, AfterViewInit, ViewChild } from "@angular/core";
import { NgEzAutocompleteDirective } from "@ngez/core";
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit{
data: string[];
@ViewChild(NgEzAutocompleteDirective) autocomplete: NgEzAutocompleteDirective;
ngAfterViewInit() {
this.autocomplete.text$
.pipe(
switchMap(query => this.apiService.getAutoComplete(query))
)
.subscribe(data=> {
this.data = data
})
}
}