简体   繁体   English

Angular 6 - 刷新组件

[英]Angular 6 - refreshing a component

I have a search box at the top of my angular page, in a header component.我的角度页面顶部有一个搜索框,位于标题组件中。

When a user submits a value in my search box, I navigate to the search results page:当用户在我的搜索框中提交一个值时,我导航到搜索结果页面:

export class SearchFormComponent {

  constructor(
    private router: Router) { }


  submit(f) {
    this.router.navigateByUrl(`search?q=${f.searchTerm}`);
  }
}

This is my results page:这是我的结果页面:

export class SearchPageComponent implements OnInit {
  results: SearchResult[];
  loading: boolean;
  searchTerm: string;

  constructor(private route: ActivatedRoute,
  private searchService: SearchService) { }

  ngOnInit() {
    this.loading = true;
    this.searchTerm = this.route.snapshot.queryParams['q'] || '';
    window.scroll(0,0)
    this.searchService.search(this.searchTerm)
      .subscribe(
        results => {
          this.results = results;
          this.loading = false;
        },
        error => {

        },
        () => {

        }
      );
  }


}

This works well on the first search, but if the user is on the search page and runs the search again from the header then it won't work.这在第一次搜索时效果很好,但如果用户在搜索页面上并从标题再次运行搜索,则它将不起作用。 What's the best way to resolve this?解决此问题的最佳方法是什么?

Angular's router has an onSameUrlNavigation event which is used to know when the router is requested to navigate to the same url so that you can refresh your component manually. Angular 的路由器有一个onSameUrlNavigation事件,用于知道何时请求路由器导航到相同的 url,以便您可以手动刷新组件。

this.router.onSameUrlNavigation(()=>{
  //do your things here
})

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

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