Angular: how to use pipe with Location

87 Views Asked by At

In Angular, Location is "A service that applications can use to interact with a browser's URL."

It offers a getState() method which providers "the current state of the location history" and a subscribe() method so one can subscribe to the "platform's popState events.".

These are both useful, however I'm wondering how I can access the observable of the Location so I can .pipe to it and use some rxjs operators before using .subscribe on it

2

There are 2 best solutions below

0
mchl18 On

Propbably not the cleanest solution but as the Location API doesn't offer anything, why not:

Subscribe to router, map to location state:


  ngOnInit() {
    const stateObservable = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(() => this.location.getState())
    );
  }

1
yurzui On

Angular library doesn't expose private internal _subject as observable of Location class.

As workaround you can create a helper to propagate the result of subscribe() method to Observable:

import { Location, PopStateEvent } from '@angular/common';
...
const locationToObservable = (location: Location) =>
    new Observable((observer: Observer<PopStateEvent>) => 
         location.subscribe(state => observer.next(state)));

Usage:

constructor(private location: Location) {
  locationToObservable(location).pipe(map(state => ...))
}