angular - 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
但页面没有刷新/重新加载。
请高手指点?
解决方案
您需要使用 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
推荐阅读
- c# - C# - 服务器端反射/动态方法调用?
- regex - awk : 设置匹配的开始和结束
- .net - Soap Web Service:如何保护它并仅由我的应用程序使用?
- webpack - HMR 与 Webpack/Laravel Mix/AdonisJS
- java - java中的正则表达式提取日期和时间
- excel - 如何使用 Power Query 更新主文件中的现有行
- c++ - SFML Release 编译中奇怪的绿色窗口边框
- r - 加载 Shinydashboard 图像
- c++ - 分层状态机涉及哪些原则,以及如何实现基本模型?
- c# - 使用用户名和密码的 Firebase 身份验证不起作用