我有一个带有Bootstrap 4.2.1的Angular 7.2.4应用程序。而且我想打电话给后端服务来填充自动完成输入框,但是即使我已经进行了简单的引导输入,但我还是遇到了麻烦。
html页面:
<div class="form-group" [class.has-danger]="searchFailed">
<label class="form-control-label" jhiTranslate="gatewayApp.legalAddress.fullAddress" for="field_fullAddress">Full Address</label>
<ng-template #rt let-r="result" let-t="term">
<ngb-highlight [result]="r.fullAddress" [term]="t"></ngb-highlight>
</ng-template>
<input type="text" class="form-control" name="fullAddress" id="field_fullAddress"
[(ngModel)]="legalAddress.fullAddress" [ngbTypeahead]="searchAddress" placeholder="n°, nome via, città"
[resultTemplate]="rt"
[resultFormatter]="formatter"
[inputFormatter]="formatter" />
<span *ngIf="searching">searching...</span>
<div class="form-control-feedback" *ngIf="searchFailed">Sorry, suggestions could not be loaded.</div>
</div>
服务:
type EntityArrayResponseType = HttpResponse<IAddress[]>;
query(req?: any): Observable<EntityArrayResponseType> {
console.log('[address.service.ts] query');
const param = new HttpParams().set('searchCriteria', ADDRESS_OTHER_TYPE_CODE);
return this.http.get<IAddress[]>(`${this.resourceUrl}/findbycriteria`, { params: param, observe: 'response' });
}
模型:
export interface IAddress {
id?: number;
addressType?: string;
...
fullAddress?: string;
}
export class Address implements IAddress {
constructor(
public id?: number,
public addressType?: string,
...
public fullAddress?: string
) {}
}
控制器:
searchAddress = (text$: Observable < string >) =>
text$.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => (this.searching = true)),
switchMap(term =>
this.geoLocalizationService.query(term).pipe(
tap(() => (this.searchFailed = false)),
catchError(() => {
this.searchFailed = true;
return of([]);
})
)
),
tap(() => (this.searching = false))
)
formatter = (x: {fullAddress: string}) => x.fullAddress;
两个问题:
1)填充fullAddress
输入框会触发searchAddress
,但是geoLocalizationService.query
始终会收到一个空的term
并将空值发送给基础后端服务
2)但是强制后端服务回馈测试结果,并不会在输入框中显示任何数据。得到这个:
[geo-localization.service.ts] query geo-localization.service.ts:18:8
ERROR Error: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
Angular 6
View_NgbTypeaheadWindow_0 NgbTypeaheadWindow.html:5
Angular 8
node_modules ng-bootstrap.js:11024
RxJS 41
Angular 8
NgbTypeaheadWindow.html:5:4
View_NgbTypeaheadWindow_0 NgbTypeaheadWindow.html:5
Angular 5
RxJS 5
Angular 11
ERROR CONTEXT
Object { view: {…}, nodeIndex: 4, nodeDef: {…}, elDef: {…}, elView: {…} }
NgbTypeaheadWindow.html:5:4
View_NgbTypeaheadWindow_0 NgbTypeaheadWindow.html:5
Angular 5
RxJS 5
Angular 11
谢谢!
==========
由于一个愚蠢的参数而解决了点1。现在,我可以正确接收后端服务了:
[[{"place_id":48841472,"licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright","osm_type":"node","osm_id":3749006665,"boundingbox":["46...","46...","13...","13...."],"lat":"46....","lon":"13....","display_name":"---","class":"place","type":"house","importance":0.411,"address":{"house_number":"5","road":"---a","neighbourhood":"---","suburb":"---","city":"---","county":"---","state":"---","postcode":"---","country":"---","country_code":"---"}}]]
现在仍然存在第2点错误,我认为是因为此服务有问题:
@Injectable({ providedIn: 'root' })
export class GeoLocalizationService {
public resourceUrl = SERVER_API_URL + 'api/geolocalization/addresses';
constructor(protected http: HttpClient) {}
query(req?: any): Observable<EntityArrayResponseType> {
console.log('[geo-localization.service.ts] query' + req);
const param = new HttpParams().set('searchString', req);
return this.http.get<IAddress[]>(this.resourceUrl, {
params: param, observe: 'response' });
}
}
这可能不是返回Observable的正确方法。我应该使用订阅返回它吗?在另一个类中,它正在工作:
provinces: IDomainBean [];
ngOnInit() {
this.legalPersonService.findAllProvinces().subscribe(
(res: HttpResponse<IDomainBean[]>) => {
this.provinces = res.body;
},
(res: HttpErrorResponse) => this.onLegalFormTypeError(res.message)
);
}
searchProvince = (text$: Observable< string >) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
map(term => term === '' ? []
: this.provinces.filter(v => v.description.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
)
formatter = (x: {description: string}) => x.description;
答案 0 :(得分:1)
几乎已解决...现在我可以通过以下更改查询服务:
1)在ngModel中使用“地址”而不是“ address.fullAddress”:
<input type="text" class="form-control" name="fullAddress" id="field_fullAddress"
[(ngModel)]="address" [ngbTypeahead]="searchAddress" placeholder="n°, nome via, città"
[resultTemplate]="rt"
[resultFormatter]="formatter"
[inputFormatter]="formatter" />
2)更改了服务:
searchAddress = (text$: Observable <string>) =>
text$.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => (this.searching = true)),
switchMap(term =>
this.geoService(term).pipe(
tap(() => (this.searchFailed = false)),
catchError(() => {
this.searchFailed = true;
return of([]);
})
)
),
tap(() => (this.searching = false))
)
formatter = (x: {fullAddress: string}) => x.fullAddress;
geoService(term: String): Observable <IGeoAddress []> {
if (term === '') {
return of([]);
}
return this.geoLocalizationService.queryGeoAddress(term).pipe(
map(res => {
return res.body.map(add => {
const addnew = new Address(
// setting initial address values
this.address.idSubject,
this.address.idContact,
add.latitude,
add.longitude,
...
);
return addnew;
});
})
);
}
它可以帮助别人还是可以改善它。