Angular 路由:Popstate 返回不会触发之前的路由

问题描述 投票:0回答:1

在我的角度应用程序上,我只有一条带有参数(语言参数)的路线:

{
  path: ":lang",
  component: MainContentComponent,
}

在我的应用程序中,每当用户想要切换语言时,我都会导航到具有不同语言参数的相同路线:

this.router.navigate([lang]);

这个概念到目前为止有效,但我有一个问题:当使用浏览器“向后一页”按钮导航回来时,URL 会更新,但组件不会使用新语言重新加载,即不会触发重新路由。

这是什么原因呢? 路由器是否有一些简单的选项可以改变这种行为?或者我是否需要以编程方式侦听事件(使用

@HostListener('window:popstate', ['$event'])
)并手动重新加载?

angular angular-routing angular-router
1个回答
0
投票

订阅ActivatedRoute Params 解决此问题的一种更以 Angular 为中心的方法是订阅组件中的路由参数并对参数的更改做出反应,而不是使用 @HostListener 监听 popstate 事件。您可以使用 Angular 的 Router 包提供的 ActivatedRoute 服务来完成此操作。

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-main-content',
  templateUrl: './main-content.component.html',
  styleUrls: ['./main-content.component.css']
})
export class MainContentComponent implements OnInit {
  private routeSub: Subscription;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // Subscribe to route parameter changes
    this.routeSub = this.route.params.subscribe(params => {
      // Extract the 'lang' parameter
      const lang = params['lang'];

      // Implement your language change logic here
      this.updateLanguage(lang);
    });
  }

  ngOnDestroy() {
    // Clean up the subscription
    if (this.routeSub) {
      this.routeSub.unsubscribe();
    }
  }

  private updateLanguage(lang: string) {
    // Your language switching logic here
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.