【发布时间】:2016-07-24 10:28:16
【问题描述】:
我在搜索时填充的页面上有一个搜索栏和结果窗格。我想要做的是在单击链接时清除结果,以便不再显示结果。
html
<input type="text" [ngFormControl]="term" class="form-control" placeholder="Search.."/>
<div *ngFor="let result of results | async" class="row search-suggestions">
<a [routerLink]="['company', result.CompanyId, 'overview']">{{result.CompanyName}}</a>
</div>
组件
export class SearchApp {
results: Observable<Array<any>>;
term = new Control();
constructor(private _router: Router,
private _searchService: SearchService) {
this.results = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this._searchService.getSearchResult(term));
}
}
我尝试订阅路由器事件并像这样清除数组:
ngOnInit() {
this._router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.results = Observable.of([]);
}
});
}
但是当我这样做并执行搜索时,_searchService 甚至没有被调用(没有网络流量)。
我看到这里的其他人问当用户使用退格键删除搜索词时如何清除数组,这对我来说适用于用户在任何地方单击路由器链接但它似乎不是最好的方法做(我什至不知道它是如何工作的)?
this._router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.results = this.term.valueChanges
.switchMap((term: string) =>
0 < term.length ? this._searchService.getSearchResult(term) : Observable.of([]));
}
});
【问题讨论】:
-
点击链接时不能清除服务中的observable吗?
<a (click)="_searchService.clearSearch()" [routerLink]="... -
这是我最初的方法,但我在同一个页面、导航和其他组件上有多个组件,我不想将相同(单击)绑定到所有组件..
标签: angular