Friday 13 May 2022

NG13 - Accessing the Previous URL in Angular

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

import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
previousUrl: string = null;
currentUrl: string = null;
constructor(private router: Router) {}

ngOnInit() {
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
});
}
}

Making it globally accessible

To make the previous url available outside of your app.component.ts file you can create a service with an observable that your components can subscribe to that holds your previous url value. Use the Angular CLI to create the service ng g s shared/url. In the url.service.ts file, you should create both a previousUrl behavior subject and observable.

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class UrlService {
private previousUrl: BehaviorSubject<string> = new BehaviorSubject<string>(null);
public previousUrl$: Observable<string> = this.previousUrl.asObservable();
...

Using a behavior subject gives you the ability to set the previous url directly. You can then set the value of the observable to the behavior subject. You will notice that I have kept the behavior subject private, this is so we can restrict access to the behavior subject. Next, in the url.service.ts file you can create a method to set the value of the previous url.

setPreviousUrl(previousUrl: string) {
this.previousUrl.next(previousUrl);
}

This sets the value of the behavior subject, which subsequently also sets the value of the observable. Now, any components that subscribe to the previous url observable will receive the updated value!

Subscribing to the previous URL observable

In any component you want to access the previous url, you need to import the url service, define it in its constructor, subscribe to the previous url observable, and set it as a variable in the component.

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { UrlService } from '../shared/url.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
previousUrl: string = '';
constructor(private urlService: UrlService) { } ngOnInit(){
// Or subscribe to the previous url observable here
this.urlService.previousUrl$
.subscribe((previousUrl: string) => {
this.previousUrl = previousUrl
});
}
}
Ref: https://jacobneterer.medium.com/accessing-the-previous-url-in-angular-32cf97bec3ce

No comments:

Post a Comment