首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >angular4订阅web服务

angular4订阅web服务
EN

Stack Overflow用户
提问于 2017-09-05 09:13:04
回答 1查看 443关注 0票数 0

我有一个在Angular4中调用的web服务(使用可观察的),并且在我的组件中(通过一个观察者和mergemap操作符)调用它。整个功能还包括材料设计,md-输入和ng-ngx-引导打字机.所有操作都是在OnInit中完成的,每次打开/刷新页面时,都会通过空查询触发对我的google服务的调用。仅当string作为参数传递时,如何触发对搜索服务的调用?我是Angular4和RxJS的新手,我的代码可能不完全正确,所以我愿意接受评论/想法/建议。

组件:

代码语言:javascript
复制
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));
}

模板:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-05 10:37:00

更换线

代码语言:javascript
复制
.mergeMap((token: string) => this.searchService.getSearch(this.value));

使用

代码语言:javascript
复制
.mergeMap((token: string) => token ? this.searchService.getSearch(this.value) : Observable.of([]));

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46051219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档