【问题标题】:How to clear an Observable array when routerlink is clicked in Angular2?在Angular2中单击routerlink时如何清除Observable数组?
【发布时间】:2016-07-24 10:28:16
【问题描述】:

我在搜索时填充的页面上有一个搜索栏和结果窗格。我想要做的是在单击链接时清除结果,以便不再显示结果。

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 甚至没有被调用(没有网络流量)。

我看到这里的其他人问当用户使用退格键删除搜索词时如何清除数组,这对我来说适用于用户在任何地方单击路由器链接但它似乎不是最好的方法做(我什至不知道它是如何工作的)?

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

【问题讨论】:

  • 点击链接时不能清除服务中的observable吗? &lt;a (click)="_searchService.clearSearch()" [routerLink]="...
  • 这是我最初的方法,但我在同一个页面、导航和其他组件上有多个组件,我不想将相同(单击)绑定到所有组件..

标签: angular


【解决方案1】:

您的SearchService 应向Observable 提供基于term.valueChanges Observable 构建的搜索结果。并依赖Router 订阅您所写的导航更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多