How to know the route before redirecting at Angular 4

Asked

Viewed 75 times

1

I have the following code snippet that redirects to a 404 page if the path is not set within the application.

{ path: '**', redirectTo: 'paginas/pagina404' }

But I would like to show on page 404 the path you tried to access, is there any way to do that? Thanks in advance!

1 answer

1

I suggest creating an event to listen to the route change in its main component relative to the <router-outlet> and publish the modifications on a service by capturing them on your 404 page. Example of how to listen:

urlAtual: string = '';
urlAnterior: string = '';

ngOnInit() {
  this.router.events.subscribe((e: any) => {
    if (e instanceof NavigationEnd) {
      this.urlAnterior = this.urlAtual;
      this.urlAtual = e.url;
    }
  });
}

After capturing the modifications you publish in your service/state management.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.