2017-09-05 144 views
0

我有一个Web服务在Angular4中调用Google Custom Search API(使用Observable),我在组件中调用它(通过Observer和mergemap运算符)。整个功能还涉及Material Design md-input和ng-ngx-bootstrap Typeahead。 一切都在OnInit中完成,每次页面打开/刷新时都会触发一次对我的谷歌搜索服务的调用,并显示一个空的查询。 只有当string作为参数传递时,我如何才能触发对我的搜索服务的呼叫?我是Angular4和RxJS Observable的新手,我的代码可能不完全正确,所以我愿意接受评论/想法/建议。angular4订阅网络服务

组件:

public value = ''; 
public dataSource: Observable<any>; 
public subs: Subscription; 

constructor(private searchService: SearchService) { } 

ngOnInit() { 
    this.dataSource = Observable 
    .create((observer: Observer<any>) => { 
     observer.next(this.value); 
     observer.complete(); 
    }) 
    .mergeMap((token: string) => this.searchService.getSearch(this.value)); 
    this.subs = this.dataSource.subscribe(x => console.log(x)); 
} 

模板:

<md-input-container class="w-75"> 
    <input mdInput [(ngModel)]="value" 
    [typeahead]="dataSource" 
    (typeaheadLoading)="changeTypeaheadLoading($event)" 
    (typeaheadNoResults)="changeTypeaheadNoResults($event)" 
    (typeaheadOnSelect)="typeaheadOnSelect($event)" 
    typeaheadOptionsLimit="10" 
    typeaheadOptionField="title" 
    typeaheadWaitMs="250" 
    typeaheadMinLength="3" 
    [typeaheadItemTemplate]="customItemTemplate" 
    placeholder="Entrez votre recherche ici"> 
    <span *ngIf="typeaheadLoading===true"><i class="fa fa-circle-o-notch fa-spin fa-fw"></i></span> 
    <div *ngIf="typeaheadNoResults===true"> 
    <i class="fa fa-times-circle-o" aria-hidden="true"></i> Aucun résultat. 
    </div> 
    <md-hint align="end">rechercher dans la sphère éducative</md-hint> 
</md-input-container> 
<button type="submit" [routerLink]="resultUrl()" md-mini-fab><i class="fa fa-search"></i></button> 
+0

试图寻找到ngModelChange叫或搜索词人。 – Swoox

回答

0

更换线

.mergeMap((token: string) => this.searchService.getSearch(this.value)); 

.mergeMap((token: string) => token ? this.searchService.getSearch(this.value) : Observable.of([])); 

所以,你的服务将只在有任何记号返回一个空数组

+0

它的工作原理!坦克你非常多Karan,我试图找出什么是该令牌的作用。 – arsrobota

+0

这里的令牌是你输入到你的输入(键入) –

+0

如果解决方案为你工作,那么你可以把它标记为有用/最好,这样的问题可以有用的其他用户 –