json - 从 Json 中提取数据以进行 ng-bootstrap typeahead

标签 json angular ng-bootstrap

尝试制作 Play Framework (REST) 和 ng-bootstrap - Typeahead一起工作。但是我在从 json 响应中提取数据时遇到了问题。例如我写“test”(通过name 在数据库中搜索),服务器返回 json 数组(一切正常):

[{
  "id": 1,
  "name": "test",
  "annotation": "test annotation",
  "kiMin": 1,
  "kiMax": 2,
  "cosFiMin": 3,
  "cosFiMax": 4
}, {
  "id": 4,
  "name": "test2",
  "annotation": "test annotation",
  "kiMin": 1,
  "kiMax": 2,
  "cosFiMin": 3,
  "cosFiMax": 4
}]

但是 View 看起来像这样:

enter image description here

这是我的代码:

http.service.ts

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Equipment }           from './equipment';
import { Observable }     from 'rxjs/Observable';
@Injectable()
export class HttpService {
  private Url = "http://localhost:9000/find?term=";  // URL to web API
  constructor (private http: Http) {}
  search ( term :String ): Observable<Equipment[]> {
    return this.http.get(this.Url+term)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }
  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

ngb-typeahead-http.ts

import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpService} from './http.service';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';


@Component({
  selector: 'ngb-typeahead-http',
  templateUrl: './typeahead-http.html',
  providers: [HttpService],
  styles: [`.form-control { width: 300px; display: inline; }`]
})
export class NgbTypeaheadHttp {
  model: any;
  searching = false;
       searchFailed = false;

    constructor(private _service: HttpService) {}

    search = (text$: Observable<string>) =>
      text$
        .debounceTime(300)
        .distinctUntilChanged()
        .do(() => this.searching = true)
  .switchMap(term =>
    this._service.search(term)
        .do(() => this.searchFailed = false)
        .catch(() => {
          this.searchFailed = true;
          return Observable.of([]);
        }))
  .do(() => this.searching = false);
  }

typeahead-http.html

<div class="form-group" [class.has-danger]="searchFailed">
  <input type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" placeholder="search" />
  <span *ngIf="searching">searching...</span>
  <div class="form-control-feedback" *ngIf="searchFailed">Sorry, suggestions could not be loaded.</div>
</div>

如何从 json 对象中提取数据?请提出任何建议。

最佳答案

当您使用预先输入的对象时,您需要使用 [inputFormatter] 和 [resultFormatter] 输入。对于 inputFormatter 和 resultFormatter,您传递的函数会从您的选择或结果列表中获取对象,并输出您想要为该对象显示的文本值。

向组件添加功能:

@Component({
  selector: 'ngb-typeahead-http',
  templateUrl: './typeahead-http.html',
  providers: [HttpService],
  styles: [`.form-control { width: 300px; display: inline; }`]
})
export class NgbTypeaheadHttp {
  model: any;
  searching = false;
  searchFailed = false;

    constructor(private _service: HttpService) {}
    // Added
    formatMatches = (value: any) => value.name || '';
    search = (text$: Observable<string>) =>
      text$
        .debounceTime(300)
        .distinctUntilChanged()
        .do(() => this.searching = true)
    .switchMap(term =>
      this._service.search(term)
          .do(() => this.searchFailed = false)
          .catch(() => {
            this.searchFailed = true;
            return Observable.of([]);
          }))
    .do(() => this.searching = false);
}

将函数传递给输入输入

<div class="form-group" [class.has-danger]="searchFailed">
    <input type="text" class="form-control"
        [(ngModel)]="model" [ngbTypeahead]="search"
        placeholder="search" 
        [resultFormatter]="formatMatches"
        [inputFormatter]="formatMatches" />
    <span *ngIf="searching">searching...</span>
    <div class="form-control-feedback" *ngIf="searchFailed">Sorry, suggestions could not be loaded.</div>
</div>

关于json - 从 Json 中提取数据以进行 ng-bootstrap typeahead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814182/

相关文章:

angular - 如何使用 Angular 2/Bootstrap 4 为 ng-bootstrap 控件自定义 CSS

angular - 如何将 bootstrap popover 绑定(bind)添加到我的 HTML?

javascript - 如何使用 Javascript 从 JSON 获取总计

c# - 使用 C# 从 Unity 中的 REST Api 中检索数据而不会出现延迟或抖动

javascript - Angular Slick slider 响应式断点 - 每个 slider 分为更小的组件

angular - 如何添加自定义 Prime NG 组件

angular - 错误 TS2742 : The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'

angular - 使用 typescript (javascript)触发 ng-bootstrap Accordion 组件?

c# - 如何将 JSON 字符串转换为 URL 参数(GET 请求)?

javascript - 在 javascript 中访问响应 Json 数据