Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

typescript - How to reload a page in Angular 8 the proper way

NB. I've got a set of resulting from googling but, as I explain at the end, I sense that they aren't reliable, due to diversity.

I have two utility methods - one for navigating to the parent node and one for reloading self. The first one works as supposed to, while the other one fails to cause the reload.

navigateToParent(route: ActivatedRoute) {
  const options: NavigationExtras = { relativeTo: route };
  this.router.navigate([".."], options);
}

navigateToSelf(route: ActivatedRoute) {
  this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  this.router.onSameUrlNavigation = "reload";
  const self = ".";
  this.router.navigate([self]);

  // const options: NavigationExtras = { relativeTo: route };
  // this.router.navigate(["."], options);
}

I followed the answer here, with the only exception that I'd like my path navigated to, to be generic, not hard-coded. I've tried passing different parameters, like self="." and self="" etc. Nothing seems to give me the desired reload.

What do I miss?

I also tried to pick the parts from the route passed into the service's method but I only see a bunch of observables, not the actual segments. And, of course, this.router.navigate(route) only caused an error.

Googling produced a lot of hints with vastly varying suggestions (e.g. this), which leads me to the suspicion that it might be heavily dependent on the version (I'm on 8.0) and, also, that many of the suggestions, although accepted, might be misleading and more harmful in the long run, without me realizing it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ok this next example works for me without reload the page:

on router component you have tu add 'onSameUrlNavigation' router.component:

@NgModule({
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
  exports: [RouterModule],
})

now component you want reload

constructor(private router: Router){
  this.router.routeReuseStrategy.shouldReuseRoute = () => {
    return false;
  };
}

someFunction(){
  this.router.navigateByUrl('/route');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...