[英]How to clear an Observable array when routerlink is clicked in Angular2?
我在页面上有一个搜索栏和结果窗格,当我进行搜索时会填充它。 我想做的是单击链接后清除结果,以使结果不再显示。
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
(没有网络流量)。
我看到这里的其他人问到当用户使用退格键删除搜索词时如何清除数组,这对我很有效,当用户单击任意位置的routerlink时,但这似乎不是最好的方法(我什至不知道它是如何工作的?
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([]));
}
});
您的SearchService
应该向Observable
提供根据term.valueChanges Observable
构建的搜索结果。 并取决于Router
来订阅您所写的导航更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.