Home > Back-end >  How can i navigate back the url in angular 14?
How can i navigate back the url in angular 14?

Time:11-07

example, i've url www.mywebsite.com/a/b/c and i want to move to www.mywebsite.com/a/b

I have tried with route.navigate(['..']) but it returns something legacy and nothing is happening.

CodePudding user response:

There is a nice and robust solution to this if you want to do it in a proper way.

There are many answers on this site that simply recommend using back() method in the Location service. However, beware that there's an edge case with that approach such that if user opens a new tab there won't be an entry in the history to go back to. This can throw user out of the Angular application as well as introduce security issues as there's no API for directly inspecting the browser history.

Following solution is based on a blog post by Nils Mehlhorn

Navigation Service

import { Injectable } from '@angular/core'
import { Location } from '@angular/common'
import { Router, NavigationEnd } from '@angular/router'

@Injectable({ providedIn: 'root' })
export class NavigationService {
  private history: string[] = []

  constructor(
    private router: Router,
    private location: Location
  ) {
    // Listen to router events of type NavigationEnd to
    // manage an app-specific navigation history.
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.history.push(event.urlAfterRedirects);
      }
    })
  }

  /**
   * Manage back navigation.
   */
  back(): void {
    this.history.pop();

    // If the history still contains entries after popping
    // the current URL off of the stack, we can safely
    // navigate back. Otherwise we're falling back to the
    // application root.
    if (this.history.length > 0) {
      console.log('navigating back')
      this.location.back();
    } else {
      console.log('navigating to /')
      this.router.navigateByUrl('/');
    }
  }

}

Back button directive

import { Directive, HostListener } from '@angular/core';
import { NavigationService } from './navigation.service';

@Directive({
  selector: '[navigateBack]',
})
export class BackButtonDirective {

  constructor(private navigation: NavigationService) {}

  @HostListener('click')
  onClick(): void {
    this.navigation.back();
  }

}

Use the directive in HTML

<button navigateBack>
   <mat-icon>arrow_back</mat-icon>Back
</button>
  • Related