angular - Bootstrap typeahead 不会传递 'term' 值并获取 "Cannot find a differ supporting object ' [object Object ]' of type ' object'

标签 angular ng-bootstrap typeahead

我有一个带有 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
    ) {}
}

Controller :

 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 并将 null 发送到底层后端服务

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;

最佳答案

几乎解决了......现在我可以通过这些更改查询服务:

1)ngModel中的“address”而不是“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;
            });
        })
    );
}

如果它可以帮助别人或者可以改进。

关于angular - Bootstrap typeahead 不会传递 'term' 值并获取 "Cannot find a differ supporting object ' [object Object ]' of type ' object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56262276/

相关文章:

css - ng-bootstrap toolip 无法添加换行符

Angular 2 - ng-bootstrap 如何为他们的 NgbRadio 指令提供 NgbRadioGroup 和 NgbButtonLabel?

mysql - 使用 MySQL 数据进行 Simpliq Bootstrap Typeahead

javascript - 如何在全局监听器上设置 javascript 属性,而无需重复代码

combobox - ExtJs 4 : Remote Combobox - Abort Previous Request

javascript - 使用rxjs实现指数补偿

angular - 如何从 mono 存储库构建 NestJs api

angular 2 HostListener - 按键空间事件在 IE 中不起作用

angular - 如何将路由附加到 ng-accordion 面板的显示?

angular - *ngFor 在 Angular 2 中失败