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:
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:
答案 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