showing results for - "how to manually trigger browser back button from angular"
Jonathan
30 May 2020
1import { Injectable } from '@angular/core'
2import { Location } from '@angular/common'
3import { Router, NavigationEnd } from '@angular/router'
4
5@Injectable({ providedIn: 'root' })
6export class NavigationService {
7  private history: string[] = []
8
9  constructor(private router: Router, private location: Location) {
10    this.router.events.subscribe((event) => {
11      if (event instanceof NavigationEnd) {
12        this.history.push(event.urlAfterRedirects)
13      }
14    })
15  }
16
17  back(): void {
18    this.history.pop()
19    if (this.history.length > 0) {
20      this.location.back()
21    } else {
22      this.router.navigateByUrl('/')
23    }
24  }
25}