从Json提取数据以提前进行ng-bootstrap [英] Extract data from Json for ng-bootstrap typeahead

查看:79
本文介绍了从Json提取数据以提前进行ng-bootstrap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图制作Play框架(REST)和 ng-bootstrap - Typeahead > 一起工作.但是我在从json响应中提取数据时遇到了一个问题.例如,我写"test"(通过name在数据库中搜索),服务器返回json数组(一切正确):

Trying to make Play Framework (REST) and ng-bootstrap - Typeahead work together. But I'm facing a problem with extracting data from json response. For example I write "test" (searches in database by name), server returns json array(everything is right):

[{
  "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
}]

但是视图看起来像这样:

But the view looks like this:

这是我的代码:

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对象提取数据?请提出任何建议.

How could I extract data from json object? Any suggestions, please.

推荐答案

在使用具有预输入功能的对象时,需要使用[inputFormatter]和[resultFormatter]输入.对于inputFormatter和resultFormatter,您传递的函数将从选择或结果列表中获取对象,并输出要为该对象显示的文本值.

When you're using objects with the typeahead you need to make use of the [inputFormatter] and [resultFormatter] inputs. For inputFormatter and resultFormatter you pass functions that take the object from your selection or results list and output the text value you want to display for that object.

向组件添加了功能:

@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提取数据以提前进行ng-bootstrap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆