问题
I have a page where on clicking a button, it will redirect using below router navigation
router.navigate (['search', {data: 'test'}]).
But when I click the same button on 2nd time without changes the values, the router.navigate won't work. How can I override that.
All thoughts are welcome!
回答1:
Angular router works this way, so if the activeRoute doesn't changed than the page/component won't be loaded again.
If you are passing parameters, like in your example: {data: 'test'} then you can watch these parameters changes by subscribing to route params:
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
// each time the search data is change you'll get this running
//Do what ever you need to refresh your search page
console.log('New route params');
});
}
回答2:
this._router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
};
this._router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this._router.navigated = false;
window.scrollTo(0, 0);
}
});
I added this to my app.component.ts ngOnInit
function, and it worked fine. All further clicks on the same link now reloads the component
and data.
Link to original GitHub feature request
Credit goes to mihaicux2 on GitHub.
I tested this on version 4.0.0-rc.3
with import { Router, NavigationEnd } from '@angular/router';
回答3:
To reload the site when navigating to the current URL again you can use the Router
ExtraOption
: onSameUrlNavigation: 'reload' (requires Angular 5.1)
const routes: Routes = [
...
];
const config: ExtraOptions = {
onSameUrlNavigation: 'reload'
};
@NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule]
})
export class AppRoutingModule { }
To call ngOnInit
of the Component to reload again, I additionally had to use:
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit(): void {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
}
来源:https://stackoverflow.com/questions/43386595/angular-2-router-navigate-not-working-2nd-time-with-the-same-url