简体   繁体   中英

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

<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).

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)?

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 . And depends on Router to subscribe to navigation changes like you wrote.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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