简体   繁体   中英

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.

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

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