继上一个问题之后,我正在使用NG-Bootstrap的预先输出功能。我的数据来自web api,采用以下格式,已从之前的格式更改。旧格式是:
result: Array(749)
[0 … 99]
0: "0000105862"
1: "0000105869"
2: "0000105875"
3: "0000110855"
4: "0000110856"
5: "0000110859"
6: "0000111068"
7: "0000111069"
8: "0000111077"
9: "0000112050"
etc
新格式是:
{
"result":[
{
"graphical":{
"link":"https://link.com",
"value":"82374982374987239487"
},
"id":{
"link":"https://links.com",
"value":"39485039485039485093485093"
},
"serial_number":"2837492837498237498"
},
]
}
我有一个服务从中输入这些数据,如下所示:
getSerials(customerId): Observable<any> {
return this.http.get<any>(this.serialApiUrl + "?customer_id=" + customerId)
.pipe(
catchError(this.handleError)
);
}
然后将其注入component.ts,如下所示:
public si_id = [];
private getSerials() {
this.service.getSerials(this.customer_id).subscribe((data) => {
for (var i = 0; i < data['result'].length; i++) {
this.si_id.push(data['result'][i]);
}
this.si_id.map(m => {
});
console.log('Data' + data);
this.loading = false;
console.log('Result - ', data);
console.log('Serial data is received');
})
}
ngOnInit() {
this.getSerials();
this.serviceForm = new FormGroup({
customer_id: new FormControl(this.customer_id),
si_id: new FormControl(this.si_id[0], Validators.required),
});
}
public model: any;
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
map(term => term === '' ? []
: this.si_id.filter(v => v.serial_number.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
)
然后在html中:
<ng-template #rt let-r="result" let-t="term">
<ngb-highlight [result]="r" [term]="t">here</ngb-highlight>
</ng-template>
<input id="si_id" type="text" placeholder="Serial number" formControlName="si_id" class="form-input"
[ngbTypeahead]="search" [resultTemplate]="rt" />
我的Typeahead有Object Object而不是数据。
目前,您的搜索流将返回this.si_id
中匹配对象的数组。您需要将筛选的项目映射到要显示的字符串:
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
map(term => term === ''
? []
: this.si_id
.filter(v => v.serial_number.toLowerCase().indexOf(term.toLowerCase()) > -1)
.slice(0, 10)
.map(v => v.serial_number) // <-- the string you want to see for each result.
)
);
如果在声明this.si_id
时设置数组的类型,可能会更有帮助。大多数IDE会显示this.search
的类型是this.si_id
类型的Observable,这样可以更容易发现问题,因为你知道你需要一串字符串而不是对象。