我有一个在Angular4中调用的web服务(使用可观察的),并且在我的组件中(通过一个观察者和mergemap操作符)调用它。整个功能还包括材料设计,md-输入和ng-ngx-引导打字机.所有操作都是在OnInit中完成的,每次打开/刷新页面时,都会通过空查询触发对我的google服务的调用。仅当string作为参数传递时,如何触发对搜索服务的调用?我是Angular4和RxJS的新手,我的代码可能不完全正确,所以我愿意接受评论/想法/建议。
组件:
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>发布于 2017-09-05 10:37:00
更换线
.mergeMap((token: string) => this.searchService.getSearch(this.value));使用
.mergeMap((token: string) => token ? this.searchService.getSearch(this.value) : Observable.of([]));因此,只有在存在任何令牌或搜索项时,才会调用您的服务,否则您将返回一个空数组。
https://stackoverflow.com/questions/46051219
复制相似问题