要在Angular中实现路由导航然后刷新页面,可以使用Router
和Location
服务的组合。
首先,在app.module.ts
中导入Router
和Location
服务:
import { Router, NavigationExtras } from '@angular/router';
import { Location } from '@angular/common';
然后在组件的构造函数中注入Router
和Location
服务:
constructor(private router: Router, private location: Location) { }
接下来,在需要导航和刷新页面的地方,使用下面的代码进行路由导航和页面刷新:
navigateAndRefresh(): void {
const currentUrl = this.router.url; // 获取当前路由的URL
// 导航到另一个路由
this.router.navigateByUrl('/other-route').then(() => {
// 刷新当前路由页面
this.location.replaceState(currentUrl);
window.location.reload();
});
}
在上面的代码中,navigateAndRefresh
方法导航到另一个路由(例如/other-route
),然后使用location.replaceState
方法将当前URL替换为原始URL,最后使用window.location.reload()
方法刷新页面。
请注意,这种方法会重新加载整个页面,可能会导致应用程序状态丢失。如果只想刷新组件的数据,可以考虑使用ngOnInit
钩子或使用@Input
属性来更新数据。