2016-07-24 55 views
0

我有一個搜索欄和結果窗格在我搜索時填充的頁面上。我想要做的是在點擊鏈接時清除結果,以便不再顯示結果。如何在Angular2中點擊routerlink時清除Observable數組?

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([])); 
    } 
}); 
+0

難道你不能只在鏈接被點擊時清除服務中的可觀察性? ' JukkaL

+0

這是我最初的方法,但在同一頁面上有多個組件,導航等等,我不想擁有將相同的(點擊)綁定到它們全部。 –

回答

0

SearchService應提供Observable與搜索結果,從term.valueChanges Observable建。並取決於Router訂閱您所寫的導航更改。