我正在致电this.router.navigate(['detailscomponent']);
,但无法致电组件的ngOninit
我尝试了下面的方法,但仍然可以正常工作,但是我必须创建一个虚拟组件,如下所示
let url:any='/valuation';
this.router.navigateByUrl('/dummy', { skipLocationChange: true });
setTimeout(() =>this.router.navigate([url,abc]));
还有其他方法可以在ts中加载oninit组件吗?
答案 0 :(得分:1)
您在这里有几种解决方案:
所有解决方案都要求您将onSameUrlNavigation添加到路由器配置:“重新加载”
@NgModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule],
})
这将全局更改所有路线的加载行为,并实际上重新渲染组件(这将触发ngOnInit)
constructor(private router: Router) {
this.router.routeReuseStrategy = () => false;
}
export class ReloadableComponent implements OnInit, OnDestroy {
private destroy$: Subject<void> = new Subject();
constructor(private router: Router) {
// subscribe to the router events.
this.router.events.pipe(
takeUntil(this.destroy$),
// If it is a NavigationEnd event re-init the component
filter(e => e instanceof NavigationEnd)
).subscribe((e: any) => {
this.refresh();
});
}
refresh() {
// Set default values and re-fetch any data you need.
}
ngOnInit(): void {
// will be called only once
this.refresh();
}
ngOnDestroy() {
// emit a value which will unsubscribe from all observables.
this.destroy$.next();
}
}
,然后将应重新加载的组件的runGuardsAndResolvers设置为“ always”(始终)
export const routes: Routes = [
{
path: 'reloadable',
component: ParentComponent,
runGuardsAndResolvers: 'always',
resolve: { data: DataResolver }
}
]
注意:runGuardsAndResolvers也会影响所有儿童的守卫和分解器
答案 1 :(得分:0)
以下是您问题的最短答案。如果您再次点击{onSameUrlNavigation:‘reload’}将重新加载当前组件。
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
很乐意提供帮助。