ark*_*ark 9 angular-routing angular
最近我听说了一个名为onSameUrlNavigation的属性,您可以在其中将其设置为“重新加载”。我在谷歌上搜索过它,但没有多少文章展示了该属性的使用。有人可以帮助我提供一个实时示例,说明我们究竟需要在哪里使用该属性。
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
Run Code Online (Sandbox Code Playgroud)
wba*_*sek 11
我遵循乔·牛顿的提示并最终得到:
@NgModule({ imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })] })
this.router.routeReuseStrategy.shouldReuseRoute = function() { return false; };
在 Angular 11 上测试。
onSameUrlNavigation 配置路由器如何处理导航到当前 URL。默认情况下,路由器将忽略此导航。但是,这会阻止诸如“刷新”按钮之类的功能。使用此选项配置导航到当前 URL 时的行为。默认值为“忽略”。通过将其设置为“重新加载”,您可以导航当前路由并通过将其设置为“忽略”来再次触发路由器事件,如果导航到同一页面,则不会更改路由,请参见此示例:
imports: [ BrowserModule, FormsModule, RouterModule.forRoot(routes, {
// onSameUrlNavigation: 'ignore',
onSameUrlNavigation: 'reload'
}) ],
Run Code Online (Sandbox Code Playgroud)
对我来说,添加onSameUrlNavigation与我的 Angular 路由完全没有区别。
当尝试从 导航/users:123到 时/users:234,该选项不允许我刷新页面。我的 Angular 页面上有复杂的网格,当我切换到不同的用户时,我特别需要处理和重新创建它们。
什么工作(现在杀了我......)是将它添加到我的代码中。
let newRouterLink = '/users:123';
this.router.navigate(['/']).then(() => { this.router.navigate([newRouterLink ]); })
Run Code Online (Sandbox Code Playgroud)
这很丑陋,但它可以完成工作......
我想将此处一些答案中的一些信息合并为一个答案。
您可以通过以下方式实现从同一路径重新加载同一组件:
app-routing.module.tsRouteReuseStrategy(返回)falserouterLink例子:
app-routing.module.ts//...
@NgModule({
// See https://angular.io/api/router/Router#properties
imports: [RouterModule.forRoot(routes, {
// onSameUrlNavigation: 'ignore', // default behavior
onSameUrlNavigation: 'reload'
})],
exports: [RouterModule],
})
export class AppRoutingModule {}
Run Code Online (Sandbox Code Playgroud)
links.component.ts(任意名称,您的会有所不同)export class LinksComponent implements OnInit {
// ...
constructor(
// ...
private router: Router) { }
ngOnInit(): void {
// ...
// With the below line you can now reload the same component from the same route
this.router.routeReuseStrategy.shouldReuseRoute = () => { return false; };
}
}
Run Code Online (Sandbox Code Playgroud)
如何处理对当前 URL 的导航请求。之一:
- 'ignore' :路由器忽略该请求。
- 'reload' :路由器重新加载 URL。用于实现“刷新”功能。
请注意,这仅配置路由是否重新处理 URL 并触发相关操作和事件,例如重定向、防护和解析器。默认情况下,当路由器重新导航到相同的组件类型而不首先访问不同的组件时,它会重新使用组件实例。此行为由 RouteReuseStrategy 配置。为了在相同的 url 导航上重新加载路由组件,您需要将 onSameUrlNavigation 设置为“重新加载”,并提供一个 RouteReuseStrategy,它为 shouldReuseRoute 返回 false。
| 归档时间: |
|
| 查看次数: |
17941 次 |
| 最近记录: |