Angular Routing: Popstate back does not trigger previous route

66 Views Asked by At

On my angular app I have only one route with a parameter (a language parameter):

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

In my app, I navigate to the same route with a different language parameter whenever the user wants to switch the language with:

this.router.navigate(["en"]);

This concept works so far, but I have one problem with it: When navigating back with the browser "Go backwards one page" button, the URL gets updated but the component is not reloaded with the new language, i.e. no rerouting is triggered.

What is the reason for that? Is there some simple option of the router which could change this behavior? Or do I need to programmaticly listen for the event (with @HostListener('window:popstate', ['$event'])) and reload manually?

1

There are 1 best solutions below

0
anis On

Subscribe to ActivatedRoute Params Instead of using @HostListener to listen for popstate events, a more Angular-centric way to address this issue is to subscribe to the route parameters in your component and react to changes in the parameters. You can do this using the ActivatedRoute service provided by Angular's Router package.

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
  }
}