Cómo determinar la URL de la página anterior en Angular?


Supongamos que estoy actualmente en la página que tiene la URL /user/:id. Ahora desde esta página navego a la siguiente página :id/posts.

Ahora hay una manera, para que pueda comprobar cuál es la URL anterior, es decir, /user/:id.

A continuación están mis rutas

export const routes: Routes = [
  { 
    path: 'user/:id', component: UserProfileComponent
  },
  {  
    path: ':id/posts', component: UserPostsComponet 
  }
];
Author: Lazar Ljubenović, 2016-12-08

6 answers

Puede suscribirse a los cambios de ruta y almacenar el evento actual para que pueda usarlo cuando suceda el siguiente

previousUrl: string;
constructor(router: Router) {
  router.events
  .filter(event => event instanceof NavigationEnd)
  .subscribe(e => {
    console.log('prev:', this.previousUrl);
    this.previousUrl = e.url;
  });
}

Véase también ¿Cómo detectar un cambio de ruta en Angular 2?

 24
Author: Günter Zöchbauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:18

Tal vez todas las demás respuestas son para angular 2.X.

Ahora no funciona para angular 5.X. Estoy trabajando con él.

Con solo NavigationEnd, no puede obtener la url anterior.

Porque el router funciona desde "NavigationStart", "RoutesRecognized",..., a "NavigationEnd".

Puede consultar con

    router.events.forEach((event) => {
  console.log(event);
});

Pero todavía no se puede obtener la url anterior, incluso con "NavigationStart".

Ahora necesita usar en parejas.

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';

constructor(private router: Router) {
  this.router.events
    .filter(e => e instanceof RoutesRecognized)
    .pairwise()
    .subscribe((event: any[]) => {
      console.log(event[0].urlAfterRedirects);
    });
}

Con pairwise, puedes ver qué url es de y para.

"RoutesRecognized" es el paso de cambio de url de origen a url de destino.

Así que filtre y obtenga la url anterior de ella.

Por último, pero no menos importante,

Este código pone el componente padre o superior (ex, app.componente.ts)

Porque este código se dispara después de finalizar el enrutamiento.

 28
Author: BYUNGJU JIN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-18 13:45:30

Crear un servicio inyectable:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';

 /** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {

  private previousUrl: string = undefined;
  private currentUrl: string = undefined;

  constructor(private router : Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {        
        this.previousUrl = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl(){
    return this.previousUrl;
  }    
}

Luego úsalo en todas partes que necesites. Para almacenar la variable actual tan pronto como sea posible, es necesario utilizar el servicio en el AppModule.

// AppModule
export class AppModule {
  constructor(private routerExtService: RouterExtService){}

  //...

}

// Using in SomeComponent
export class SomeComponent implements OnInit {

  constructor(private routerExtService: RouterExtService, private location: Location) { } 

  public back(): void {
    this.location.back();
  }

  //Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
  public goToPrevious(): void {
    let previous = this.routerExtService.getPreviousUrl();

    if(previous)
      this.routerExtService.router.navigateByUrl(previous);
  }

  //...

}
 12
Author: Juliano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-29 01:02:38

Angular 6 código actualizado para obtener la url anterior como cadena.

import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';


export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

    ngOnInit() {
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects); // previous url
            });
    }
 3
Author: Franklin Pious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-16 07:24:00

@GünterZöchbauer también puedes guardarlo en localstorage pero no lo prefiero ) mejor ahorrar en el servicio y obtener este valor desde allí

 constructor(
        private router: Router
      ) {
        this.router.events
          .subscribe((event) => {
            if (event instanceof NavigationEnd) {
              localStorage.setItem('previousUrl', event.url);
            }
          });
      }
 1
Author: vladymy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-17 12:00:37

Tuve un problema similar cuando quería volver a la página anterior. La solución fue más fácil de lo que podía imaginar.

<button [routerLink]="['../']">
   Back
</button>

Y vuelve a la url principal. Espero que ayude a alguien ;)

 -5
Author: DiPix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-09 11:52:14