Sre*_*lli 45 components routes refresh angular
我正在开展Angular项目.我正在努力应对组件中的刷新操作.
我想在按钮点击时刷新路由器的组件.当我点击它时,我有刷新按钮需要刷新组件/路由器.
我试过window.location.reload(),location.reload()这两个不适合我的需要.如果有人知道,请帮忙.
Sre*_*lli 77
经过一些研究和修改我的代码如下,该脚本为我工作.我刚刚添加条件:
this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this.router.navigate(['Your actualComponent']);
});
Run Code Online (Sandbox Code Playgroud)
Shi*_*abu 38
使用this.ngOnInit(); 重新加载相同的组件,而不是重新加载整个页面!
DeleteEmployee(id:number)
{
this.employeeService.deleteEmployee(id)
.subscribe(
(data) =>{
console.log(data);
this.ngOnInit();
}),
err => {
console.log("Error");
}
}
Run Code Online (Sandbox Code Playgroud)
小智 20
将此代码添加到所需组件的构造函数的代码中.
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return 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)
请务必unsubscribe从此mySubscription中进行操作ngOnDestroy().
ngOnDestroy() {
if (this.mySubscription) {
this.mySubscription.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此主题 - https://github.com/angular/angular/issues/13831
Fen*_*ang 18
调用ngOnInit()不适用于我的复杂组件,我最终使用了这个
reloadCurrentRoute() {
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
Run Code Online (Sandbox Code Playgroud)
Abh*_*wat 10
只需按照以下步骤操作:
{onSameUrlNavigation: 'reload'}如下内容@NgModule({
导入: [ RouterModule.forRoot(routes,{onSameUrlNavigation: 'reload'})],
导出: [ RouterModule ]
})
this.router.routeReuseStrategy.shouldReuseRoute = () => false在组件 ts 文件构造函数中添加如下内容:Run Code Online (Sandbox Code Playgroud)constructor(private router: Router) { this.router.routeReuseStrategy.shouldReuseRoute = () => false; }
this.router.navigate([/sameRoute]);最后打电话 。将 SameRoute 替换为您的路线 url。我正在使用 Angular 12。
幸运的是,如果您使用的是Angular 5.1+,则不再需要实施hack,因为已添加了本机支持.您只需要在RouterModule选项中将onSameUrlNavigation 设置为'reload':
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到:https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
没有明确路由的另一种方式:
async reload(url: string): Promise<boolean> {
await this.router.navigateByUrl('.', { skipLocationChange: true });
return this.router.navigateByUrl(url);
}
Run Code Online (Sandbox Code Playgroud)
这可以通过 hack 来实现,导航到一些示例组件,然后导航到要重新加载的组件。
this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
162061 次 |
| 最近记录: |