Angular路由切换时组件显示状态未重置问题求助
问题:切换服务器路由后页面空白无法回到初始状态
我被这个问题卡了3小时,需求如下:
- 组件初始加载时显示服务器信息区域
- 点击“Edit Server”按钮后,该区域隐藏,显示
router-outlet内容 - 切换服务器路由时,需将
display重置为true,回到初始显示状态
但目前切换服务器后页面空白,相关代码如下:
Server Template HTML
<!-- When the component first opens, I want this first div to display. Howeever, when I click the button I want it to disapper and router-outlet to show up. When I change servers, I want 'display' to be true --> <div *ngIf="display"> <h5>{{ server.name }}</h5> <p>Server status is {{ server.status }}</p> <button class="btn btn-primary" (click)="onEdit()">Edit Server</button> </div> <!-- When I change servers, this whole template disappears. --> <div> <router-outlet></router-outlet> </div>
Server Component TS
export class ServerComponent implements OnInit { server: {id: number, name: string, status: string}; id: number display: boolean = true URLid: number constructor(private serversService: ServersService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { // This just captures the id in the url and it searches for its respective server this.id = +this.route.snapshot.params['id'] this.server = this.serversService.getServer(this.id) this.route.params.subscribe((params: Params) => { this.id = +this.route.snapshot.params['id'] this.server = this.serversService.getServer(this.id) }) } onEdit() { /* When the button is clicked, display is set to false. This in turn, makes it so only 'router-outlet' is displayed. However, when the server is changed, everything disappears. */ this.display = !this.display this.route.params.subscribe(params => { this.URLid = params['id'] }) this.router.navigate(['edit'], {relativeTo: this.route}) } }
EditServer Template
<h4>No editing the server!</h4>
状态说明
- 初始状态:显示服务器信息
- 点击“Edit Server”后,正常显示
router-outlet内容 - 切换服务器路由(如切换到Devserver)后,页面空白,无法回到初始状态
问题原因及修复方案
核心问题
切换服务器路由时,display变量没有被重置为true,导致服务器信息区域不显示;同时切换服务器后编辑路由已失效,router-outlet里也没有内容,最终页面空白。另外onEdit方法里存在完全冗余的路由参数订阅。
修复步骤
1. 在路由参数变化时重置display
修改ngOnInit里的路由参数订阅逻辑,每次切换服务器(参数变化)时强制把display设为true,同时优化参数获取方式(直接用订阅返回的params,比snapshot更可靠):
ngOnInit() { // 初始加载获取服务器 this.id = +this.route.snapshot.params['id']; this.server = this.serversService.getServer(this.id); // 监听路由参数变化,切换服务器时重置状态 this.route.params.subscribe((params: Params) => { this.id = +params['id']; this.server = this.serversService.getServer(this.id); this.display = true; // 关键:切换服务器时重置display为初始状态 }); }
2. 移除onEdit里多余的订阅
onEdit方法中的this.route.params.subscribe是冗余代码,直接删除即可,切换服务器的逻辑已经在ngOnInit的订阅里处理完毕:
onEdit() { this.display = !this.display; this.router.navigate(['edit'], {relativeTo: this.route}); }
3. 效果验证
修改后:
- 切换服务器路由时,
display自动重置为true,服务器信息区域正常显示 - 点击编辑按钮后,
display变为false,显示router-outlet内容 - 从编辑状态切换服务器,会自动回到服务器信息显示状态
内容的提问来源于stack exchange,提问作者Yousef
相关产品推荐
相关产品推荐

