簡體   English   中英

在Angular2中單擊routerlink時,如何清除Observable數組?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM