Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reactively subscribe to URL change and get URL in Angular RxJS?

I have application with routing, which changes by buttons click (see screen below). I'm trying to get URL into text box every time it's changes. How to do it? So far I been able to attach to ActivatedRoute.queryParams , but it fires only if there are parameter change, and do not work without parameter.

// could you help to fix this code?  
url$ = this.activatedRoute.queryParams.pipe(
    map(() => {
      console.log("router.url="+this.router.url); // full URL with params
      return this.router.url.split('?')[0] ;
    })
  )

I'm changing pages by button click code:

  btnGoProducts(name?: string){
    if (name)
      this.router.navigate(['/products'], {queryParams: {name: name}});
    else
      this.router.navigate(['/products']);
  } 

Only right buttons on this screen works (because subscription on the parameters change):

enter image description here

Page code: app.component.ts Whole test app: github.com/sam-klok/AngularPlayRoutes

like image 486
sam klok Avatar asked Sep 14 '25 18:09

sam klok


1 Answers

I'm not sure if I understood you, you are subscribed to queryParams so it will detect when they are changed, if you want to detect route changes and get the whole url (with query parameters) as an Observable you can try this on url$:

Imports:

import { Router, NavigationEnd } from '@angular/router';
import { map, filter } from 'rxjs/operators';

Declaring variable url$:

 url$: Observable<string> = new Observable<string>();

Setting url$ value:

this.url$ = this.router.events.pipe(
  filter((event: any) => event instanceof NavigationEnd),
  map((event: NavigationEnd) => event.url)
);
like image 197
Bobe Avatar answered Sep 17 '25 08:09

Bobe