rxjs Subject - clear?

时间:2017-04-10 02:20:09

标签: angular rxjs

I ran through the Tour of Heroes tutorial and changed a bit. I moved the search field to the nav bar. On search, it does a dropdown search:

search bar

Clicking on any of the li in the group will navigate to the detail page of each hero. The issue I am having is that navigation doesn't clear the search term. This is my current function:

export class HeroSearchComponent implements OnInit {
  heroes: Observable<Hero[]>;
  private searchTerms = new Subject<string>();
 ...
  gotoDetail(hero: Hero): void {
    let link = ['/detail', hero.id];
    this.router.navigate(link);
  }

My thought was that I could call this.searchTerms.clear() if such a method existed, but I'm not too familiar with rxjs subjects. I could also reinitialize it:

this.searchTerms = new Subject<string>();

but wouldn't this create a new object every time I search? What is the best way to solve this?

In addition, I'm not sure that this navigate is working. When I navigate this way, it doesn't seem to use the @Input() that is in a sub component.

Edit: deployed on heroku for people to see the issue. To replicate:

  1. go to a 'hero detail' page of hero 11:
    • note the spinning svg. This is the spinner img component. When the img cannot be found (or is loading), it defaults to a spinner img. OnLoad changes the image to the actual image. hero 11 does not have an image, so the spinner stays (desired effect).
  2. type "m" in the search bar in the nav.
  3. click on Bombasto. Note the pic loads
  4. click on Mr. Nice (no pic). Note that there is now no image (although this is hero 11, and we had a spinner before).

1 个答案:

答案 0 :(得分:3)

主题不存储搜索词框的值,它只是发出

的当前值
<input #searchBox> 

每次都有一个keyup事件。主题根本不存储最后一个发射的值,因此如果要清除搜索框,则需要将输入框的值设置为“”。例如。在您的英雄搜索组件中添加以下属性

@ViewChild('searchBox') searchBox: ElementRef; 

然后在gotoDetail方法中:

gotoDetail(hero: Hero): void {
    this.searchBox.nativeElement.value = '';
    let link = ['/detail', hero.id];
    this.router.navigate(link);
}

使用主题不是建议的方法,但对初学者来说没问题。更好的方法是从DOM元素上的keyup事件创建一个Observable direct - 这里有一个这种方法的例子 - https://github.com/Reactive-Extensions/RxJS/blob/master/examples/autocomplete/autocomplete.js