如何刷新Angular中的组件

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)

  • 大多数人都可以使用`/'来代替,其中`/ RefrshComponent`是,对于[[Your ActualComponent“]`,您只需传递要重新加载的url(和/或params),例如“ this”。 router.navigate([“ / items”])`。该hack本质上将重定向到顶部URL,然后非常快速地返回到预期的URL,该URL对大多数用户而言并不为人所知,并且似乎是最简单地实现此目的的hack。 (7认同)
  • 你能解释一下什么是“RefrshComponent”和“Your actualComponent”吗? (6认同)
  • 我同意这绝对可以工作......但它在我的应用程序(Angular 6)中失败了。如果我使用 `'/'` 作为我的虚拟路由,它会(通过 `redirectTo`)到达我的 app-routing.module.ts 重定向到 `''`(空字符串)的路径并停止,而不是继续`navigate()` 调用中的完成路由。如果我使用一个不存在的字符串(例如 `/foo`)作为我的虚拟路由,它会(通过 `redirectTo`)到我的 app-routing.module.ts 重定向到 `**`(其他所有内容)的地方,然后再次停止,不去真正的路线。奇怪的是,URL 栏确实更改为真实路由。关于这里有什么不同的任何想法? (4认同)
  • 我在可注射服务中使用它。我用一个变量替换了“你的实际组件”。在调用 `navigateByUrl` 之前,该变量设置为 [`this.location.path()`](https://angular.io/api/common/Location#path)。这样,无需从调用组件或复制/传递路由传递任何参数。 (2认同)

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)

  • ngOnInit 是 Angular 调用的生命周期方法。你不应该自己称呼它。如果您想再次执行 ngOnInit 中的某些逻辑,只需将其移动到一个方法中并调用该方法即可。 (8认同)
  • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和/或文档链接.如果没有一些短语,原始代码片段就不是很有用.你也可以找到[如何写出一个好的答案](https://stackoverflow.com/help/how-to-answer)非常有帮助.请编辑你的答案. (4认同)
  • 尽管它适用于组件,但它不会重置表单验证器。 (4认同)
  • 工作完美,谢谢。关于 AFAIC 的解释,代码说明了一切。 (4认同)
  • 同意,这仅在您要从组件内部刷新组件时才有效-如果要处理子组件/外部组件,则此.ngOnInit()将不起作用 (3认同)
  • 非常简洁,谢谢 (2认同)
  • 这是比所选答案更好的输入,但缺乏解释。在我的特定情况下,我必须刷新子组件。在这种情况下,有几种方法,但建议使用服务或从父级向子级广播事件。 (2认同)

小智 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)


小智 10

这有点开箱即用,我不知道这是否对您有帮助,但您是否尝试过

this.ngOnInit();

它是一个函数,因此您在其中包含的任何代码都将像刷新一样被调用。


Abh*_*wat 10

只需按照以下步骤操作:

  1. 在您的 app-routing.modules.ts 中添加{onSameUrlNavigation: 'reload'}如下内容

@NgModule({
导入: [ RouterModule.forRoot(routes,{onSameUrlNavigation: 'reload'})],
导出: [ RouterModule ]
})

  1. this.router.routeReuseStrategy.shouldReuseRoute = () => false在组件 ts 文件构造函数中添加如下内容:
constructor(private router: Router) {
      this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  }
Run Code Online (Sandbox Code Playgroud)
  1. 现在单击按钮并调用 ajax 服务器调用,从服务器获取所需的数据并用新数据替换 TS 文件中的全局变量。
  2. this.router.navigate([/sameRoute]);最后打电话 。将 SameRoute 替换为您的路线 url。

  3. 确保在刷新按钮的 onClick 方法末尾返回 false,否则将导致主路由页面而不是同一页面重新加载。

    这些步骤将重新加载您的页面。:)

有关更多详细信息: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

我正在使用 Angular 12。


Luc*_*van 8

幸运的是,如果您使用的是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

  • 使用角度6,对我而言这没有什么区别,也就是说,组件没有重新加载。但是,可接受的答案有效。 (3认同)
  • 尽管在文档中并不十分清楚,`onSameUrlNavigation`旨在重新调用Guards / Resolvers,而不是重新加载已路由的组件。有关更多信息,请参见https://github.com/angular/angular/issues/21115。该解决方案将适用于使用Guards / Resolver的大型更复杂的应用程序,但对于简单的示例将失败。 (2认同)
  • 是的,onSameUrlNavigation 将再次触发导航事件,但这不会重新加载组件 (2认同)

Fel*_*lix 7

没有明确路由的另一种方式:

async reload(url: string): Promise<boolean> {
  await this.router.navigateByUrl('.', { skipLocationChange: true });
  return this.router.navigateByUrl(url);
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上它给出了错误:无法匹配任何路由。URL 段:“.” 如果你的应用程序路由中没有该路由 (2认同)

Saj*_*ran 5

这可以通过 hack 来实现,导航到一些示例组件,然后导航到要重新加载的组件。

this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);
Run Code Online (Sandbox Code Playgroud)

  • 它应该是一个虚拟的,可以为空 (2认同)