2017-05-16 2 views
1

자동 완성을 위해 Angular 4 Typeahead에 ngBootstrap을 사용하고 싶습니다. 원격 데이터 검색에 사용 된 예제는 http가 아닌 Jsonp를 사용하고 있습니다. 그 예제에서 Jsonp를 http로 대체하기위한 정보를 더 찾으려고 노력했습니다. 나는 Observables에 너무 익숙하지 않아서 나는 그것들을 배우고 그들에 대해 더 잘 이해하려고 노력하고있다.ngBootstrap에 http를 사용하여 각도 4에 대해 Typeahead 사용

나는이 example을 보았지만 은 실제로으로 보이며 간단하게 (?) 나뭇잎을 많이 낸다 ... 단순성을 위해?

누군가 올바른 방향을 가리킬 수 있습니까? ngBootstrap Typeahead와 함께 http를 사용하여 좋은 예를 찾고 있습니다.

편집

{ 
    "took": 15, 
    "timed_out": false, 
    "_shards": { 
    "total": 1, 
    "successful": 1, 
    "failed": 0 
    }, 
    "hits": { 
    "total": 9, 
    "max_score": 4.2456956, 
    "hits": [ 
     { 
     "_index": "query-index", 
     "_type": "autocomplete", 
     "_id": "AVxqBE-3t2o4jx2g0ntb", 
     "_score": 4.2456956, 
     "_source": { 
      "suggestions": "bruce" 
     } 
     }, 
     { 
     "_index": "query-index", 
     "_type": "autocomplete", 
     "_id": "AVxqBE-3t2o4jx2g0ntc", 
     "_score": 3.064434, 
     "_source": { 
      "suggestions": "bruce wayne" 
     } 
     }, 
     { 
     "_index": "query-index", 
     "_type": "autocomplete", 
     "_id": "AVxqBE-3t2o4jx2g0ntd", 
     "_score": 3.064434, 
     "_source": { 
      "suggestions": "bruce willis" 
     } 
     }, 

편집 2

export class AutocompleteComponent { 
    model: any; 
    searching = false; 
    searchFailed = false; 

    constructor(private autocompleteService: Elasticsearch) {} 

    //formatMatches = (query: any) => query.hits.hits._source.suggestions || ''; 
    //formatMatches = (query: any) => query.hits.hits || ''; 
    formatMatches = (query: any) => <any>response.json().hits.hits || ''; 
    search = (text$: Observable<string>) => 
    //search = (text$: Observable<Suggestion[]>) => 
    text$ 
     .debounceTime(300) 
     .distinctUntilChanged() 
     //.switchMap(term => 
     //Observable.fromPromise(this.autocompleteService.search(term) 
     .switchMap(term => 
     this.autocompleteService.search(term) 
     .do(() => this.searchFailed = false) 
     .catch(() => { 
     this.searchFailed = true; 
     return Observable.of([]); 
     })) 
     .do(() => this.searching = false); 
} 
+0

나는 내가 나의 일을 찾은 것 같아,하지만 난 그것을 한 방법을 정확하게 확실하지 ma에. 여기에 게시 한 예를 사용했습니다. –

답변

2

는 내가 그것을 설명하는 방법을 조금 알 것 같아요. 그러나 저는 필터를 다루는 모달을 만들고 있습니다. 아래는 내 httpService입니다. 검색 문자열을받는 getCarriers.

내 모달 구성 요소에서
getCarriers(query: string): Observable<any> { 
    return this._http.get(this._ripcord + '/carriers?search_string=' + query, this.options) 
    .map((response: Response) => <any>response.json().data) 
    .do(data => console.log(data)) 
    .catch(this.handleError); 
} 

에게 (filters.component.ts) 파일 내 서비스는 객체의 배열을 반환하는 것을 알고, 나는 포맷터를 입력뿐만 아니라 결과 개체를 모두 처리 할 수 ​​ 방법을 만들어야했습니다 구조.

나는 ngbdTypeahead가 Observable을 받아들이므로 내 httpservice에이 용어를 보내고 구독하려고 시도하는 대신 Observable을 반환 할 수 있다고 생각했습니다.

// filters.modal.html 
<div class="modal-header"> 
    <h4 class="modal-title">Hi there!</h4> 
    <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')"> 
    <span aria-hidden="true">&times;</span> 
    </button> 
</div> 
<div class="modal-body"> 
    <!--<p>Hello, {{name}}!</p>--> 
    <form [formGroup]="filtersForm" novalidate> 
    <div class="form-group"> 
     <label class="center-block">Carrier: 
     <input type="text" class="form-control" formControlName="name" [ngbTypeahead]="carrier_search" [inputFormatter]="formatter" [resultFormatter]="formatter"> 
     </label> 
    </div> 
    </form> 

    <p>Form value: {{ filtersForm.value | json }}</p> 
    <p>Form status: {{ filtersForm.status | json }}</p> 
</div> 
<div class="modal-footer"> 
    <button type="button" class="btn btn-secondary" (click)="activeModal.close('Close click')">Close</button> 
</div> 

어떤 구체적인 질문이 있으면 알려주세요 :

// filters.component.ts 
import { Component, OnInit } from '@angular/core'; 
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; 
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 
import { Observable } from 'rxjs/Observable'; 
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'; 

import { HttpService } from '../../../shared/http.service'; 
import { Carrier } from '../../../definitions/carrier'; 

@Component({ 
    selector: 'afn-ngbd-modal-content', 
    templateUrl: './modal/filters.modal.html', 
    styleUrls: ['./modal/filters.modal.css'] 
}) 
export class NgbdModalContentComponent { 

    filtersForm: FormGroup; 
    carriers: Carrier[]; 

    constructor(public activeModal: NgbActiveModal, public httpService: HttpService, private fb: FormBuilder) { 
    this.createForm(); 
    } 

    carrier_search = (text$: Observable<string>) => 
    text$ 
     .debounceTime(200) 
     .distinctUntilChanged() 
     .do((text) => console.log(text)) 
     .switchMap(term => 
     this.httpService.getCarriers(term) 
    ) 
    ; 

    formatter = (x: {attributes: {name: string}}) => x.attributes.name; 

    createForm() { 
    this.filtersForm = this.fb.group({ 
     name: ['', Validators.required], 
    }); 
    } 
} 

@Component({ 
    selector: 'afn-filters', 
    templateUrl: './filters.component.html', 
    styleUrls: ['./filters.component.css'] 
}) 
export class FiltersComponent implements OnInit { 

    constructor(private modalService: NgbModal) { } 

    open() { 
    const modalRef = this.modalService.open(NgbdModalContentComponent); 
    } 
    ngOnInit() { 
    } 

} 

여기 내 HTML의 내 모달를위한 템플릿입니다. 내가 일할 때까지 나는 일종의 해킹을 당했다.

말할 필요도없이, debounceTime이 멋지더라도, 사용자가 최소 3자를 입력 할 때까지 요청을 실행하고 싶지 않습니다. 스위치 맵 내에 논리를 넣으려고하면 오류가 발생합니다.

enter image description here

+0

지금이 문제가 다시 발생하면 몇 가지 사항을 처리해야합니다. 포맷터 기능을 좀 더 설명 할 수 있습니까? 나는 당신이하는 것과 똑같은 계약을 맺고 있고, 내 서비스는 Elasticsearch를 사용하여 객체 배열을 리턴한다. – user3125823

+0

포맷터 함수 표현식은 동적 요청에서 제공된 각 객체를 가져 와서 렌더링 할 기존 등록 정보로 드릴 다운합니다. Elasticsearch에서 겪고있는 문제점은 무엇입니까? 어떤 종류의 데이터 표현이 반환됩니까? –

+0

위의 Edit에 내가받은 ES 반환 샘플을 추가했습니다. 나는 "제안"의 텍스트 값을 드릴 다운하는 방법을 모르겠습니다. – user3125823