Kon*_*ten 3 router typescript angular angular8
注意。我通过谷歌搜索得到了一组结果,但正如我最后解释的那样,由于多样性,我觉得它们不可靠。
我有两种实用方法 - 一种用于导航到父节点,一种用于重新加载 self. 第一个按预期工作,而另一个无法导致重新加载。
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);
}
Run Code Online (Sandbox Code Playgroud)
我遵循了这里的答案,唯一的例外是我希望我的路径导航到通用,而不是硬编码。我试过传递不同的参数,比如self="。" 和self=""等。似乎没有什么能给我想要的重新加载。
我想念什么?
我还尝试从传递到服务方法的路由中挑选部分,但我只看到一堆可观察的,而不是实际的段。而且,当然,this.router.navigate(route)只会导致错误。
谷歌搜索产生了很多提示,其中包含大量不同的建议(例如this),这让我怀疑它可能严重依赖于版本(我使用的是 8.0),而且,许多建议虽然被接受了,从长远来看,可能会产生误导,更有害,而我没有意识到这一点。
小智 9
好的,下一个示例适用于我而无需重新加载页面:
在路由器组件上,您必须添加 'onSameUrlNavigation' router.component:
@NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule],
})
Run Code Online (Sandbox Code Playgroud)
现在要重新加载的组件
constructor(private router: Router){
this.router.routeReuseStrategy.shouldReuseRoute = () => {
return false;
};
}
someFunction(){
this.router.navigateByUrl('/route');
}
Run Code Online (Sandbox Code Playgroud)
您可以在此StackBlitz 链接中找到完整的工作示例
更新
首先这样做window.location.reload()
完全违背了单页应用程序的性质。相反,您可以在实际单击该链接时重新加载特定组件.. 所以,为了完成这项任务,我们有 angular router。对于特定的组件重新加载,您可以将这行代码推送到主app.component.ts 中一次以获得完整的应用程序。
mySubscription;
constructor(private router: Router, private activatedRoute: ActivatedRoute){
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.mySubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
// Trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
}
});
}
Run Code Online (Sandbox Code Playgroud)
上面的代码中,我们要subscribing
到router-events
。然后我们检查每个router-NavigationEnd
事件,然后告诉路由器,忘记将路由器的当前导航添加到它自己的历史记录中。因此,每当我们尝试重新加载相同的组件时,每个事件都只针对该特定组件触发,这就是 SPA。
在app.component.ts中ngOnDestroy()
,当组件被销毁时,我们必须取消订阅路由器事件。
ngOnDestroy(){
if (this.mySubscription) {
this.mySubscription.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,例如您有 Home 和 Details 组件或任何其他组件......您可以通过调用重新加载每个组件来this.router.navigate([this.router.url])
重新加载所有当前组件。例如,在home component
我们reload-button
刚刚调用的点击事件中this.router.navigate([this.router.url])
。细节组件也一样..或任何其他组件..
主页.component.ts
reLoad(){
this.router.navigate([this.router.url])
}
Run Code Online (Sandbox Code Playgroud)
详细信息.component.ts
reLoad(){
this.router.navigate([this.router.url])
}
Run Code Online (Sandbox Code Playgroud)
您可以在 StackBlitz 链接上方检查更新,所有使用完整路由器状态重新加载的重新加载示例。在浏览器控制台中,通过单击按钮查看组件的每个事件正在触发reload()
。
归档时间: |
|
查看次数: |
25096 次 |
最近记录: |