0

I am using Angular 13 and I am trying to subscribe to the ActivatedRoute 'fragment'. The subscription is only receiving a notification when the page first loads, but is not receiving updates when the fragment gets updated.

Here is an example of what I am doing:

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

@Component({
    selector: 'app-my-component',
    templateUrl: './my-component.component.html'
})
export class MyComponentComponent implements OnInit {
    constructor(private activatedRoute: ActivatedRoute) { }

    ngOnInit(): void {
        this.activatedRoute.fragment.subscribe((fragment: string) => {
            console.log("test page: ", fragment)
        });
    }
}

I would expect that on page load, and every time the fragment changes I would receive a notification to this subscription.

What I am actually experiencing is that this subscription is only notified on the initial page load, and not on any subsequent changes.

Anker Peet
  • 41
  • 8

1 Answers1

0

you need to subscribe to the router events:

import { Router, NavigationEnd, Subscription } from '@angular/router';

@Component({
  templateUrl: './my-component.component.html',
  styleUrls: [
    './my-component.component.scss'
  ]
})
export class MyComponent implements OnInit, OnDestroy
{
  private routerSubscription:Subscription;
  
  public constructor(
    private router:Router
  ){}

  public ngOnInit(): void
  {
    this.routerSubscription = this.router.events.subscribe(event => {

        if(event instanceof NavigationEnd)
          console.log( event.url); // do something here...
    });

  }
  
  public ngOnDestroy():void
  {
    this.routerSubscription?.unsubscribe();
  }
}
Juan Castillo
  • 66
  • 1
  • 9
  • Subscribing to the RouterEvents does not subscribe to the URL fragment. You only get notifications with this when the route or the query params update, but any changes to the fragment(anything after the "#" symbol) do not trigger changes. – Anker Peet Dec 21 '22 at 20:00