首页 > 解决方案 > Angular 7:在参数更改时刷新页面

问题描述

我已经在 Angular 7 中创建了应用程序。在导航部分,当浏览器 url 中的参数发生变化时,页面不会刷新。

前任:

用户点击学科菜单项,页面 url 看起来像 http://localhost:4200/xxx/disciplines

用户点击学科页面中的表格行项目,网址看起来像 http://localhost:4200/xxx/disciplines?disciplineId=1150

当用户再次单击学科菜单项时,浏览器 url 中的 url 会正确更改, http://localhost:4200/xxx/disciplines但页面没有刷新/重新加载。

请高手指点?

标签: angularrouting

解决方案


您需要使用 Angular Router 中的 ActivatedRoute :

从'@angular/router'导入{ActivatedRoute};

然后,您必须将其注入组件的构造函数中:

构造函数(私有路由:ActivatedRoute)

在您的 ngOnInit 中,您只需订阅路线上发生的更改:

this.routeSubscription = this.route.params.subscribe((param: any) => {
this.id = param['disciplineId'];
this.yourSpecialFunction();
});

重要提示:我总是创建一个订阅者属性:

import { Subscription } from 'rxjs';
...
...
导出类 YourComponent 实现 OnInit, OnDestroy {
private routeSubscription: Subscription

确保组件实现 OnDestroy 并在 ngOnDestroy() 方法中:

ngOnDestroy() { this.routeSubscription.unsubscribe(); }

您必须取消订阅应用程序中的每个订阅以避免内存泄漏。

更多订阅信息,请参考这篇 Tomas Trajan 的文章:https ://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0


推荐阅读