繁体   English   中英

angular4订阅Web服务

[英]angular4 subscribe to a web service

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

零件:

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>

更换线

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

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

因此,只有在有任何令牌或搜索字词时才会调用您的服务,否则您将返回一个空数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM