简体   繁体   English

在Angular2中单击routerlink时,如何清除Observable数组?

[英]How to clear an Observable array when routerlink is clicked in Angular2?

I have a search bar and results pane on a page that gets populated when I search. 我在页面上有一个搜索栏和结果窗格,当我进行搜索时会填充它。 What I want to do is to clear the result when a link is clicked so that the result isn't shown anymore. 我想做的是单击链接后清除结果,以使结果不再显示。

html 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>

component 零件

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));
  }
}

I tried to subscribe to router events and clear the array like so: 我试图订阅路由器事件并清除数组,如下所示:

  ngOnInit() {
    this._router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.results = Observable.of([]);
      }
    });
  }

But when I do this and perform a search the _searchService isn't even called (no network traffic). 但是,当我这样做并执行搜索时,甚至没有调用_searchService (没有网络流量)。

I saw that someone else on here asked how to clear the array when the user use backspace to erase the search term and this works for me to when a user clicks on a routerlink anywhere but it doesn't seem the best way to do it (I don't even know how it works)? 我看到这里的其他人问到当用户使用退格键删除搜索词时如何清除数组,这对我很有效,当用户单击任意位置的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([]));
  }
});

Your SearchService should provide the Observable with search results, built from the term.valueChanges Observable . 您的SearchService应该向Observable提供根据term.valueChanges Observable构建的搜索结果。 And depends on Router to subscribe to navigation changes like you wrote. 并取决于Router来订阅您所写的导航更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM