问题出现的原因是路由导航后组件并没有被销毁和重新创建,因此显示旧信息。可通过使用路由器的“NavigationEnd”事件来更新组件并重新加载数据。
在组件的构造函数中注入“Router”和“ActivatedRoute”,然后在“ngOnInit”生命周期钩子中订阅“NavigationEnd”事件。在订阅中更新组件并重新加载数据。
示例代码如下:
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponentComponent implements OnInit {
constructor( private router: Router, private route: ActivatedRoute ) { }
ngOnInit() { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { //update component and reload data } }); } }
通过以上修改,即可解决路由导航后页面显示旧信息的问题。