2

I have the following configuration of routes:

{ loadChildren: './public#PublicModule', path: '' },
{ loadChildren: './home#HomeModule', path: 'home' },
{ path: '**', redirectTo: '/404' }

In some template (if it matters, let's call it xxx.component.html) I created a button to make some tests in my 404 route:

<button type="button" routerLink="unknown">Click here for unknown</button>

With this, I'm in route home/xxx and after press the button, it works, I mean it goes to 404 page, however, the following is returned for me:

NavigationEnd {id: 2, url: "/home/unknown", urlAfterRedirects: "/404"}

But I was expecting to get the REAL previous route (home/xxx), not the URL that I set in my button. Is there a way to achieve this?

PS1: I tried to use pairwise, but it only works after call the 404 route 2 times.

My 404 component looks like:

export class NotFoundErrorComponent {

  public previousUrl: string;

  constructor(
    private router: Router
  ) {
    this.router.events
    .filter((event: any) => event instanceof NavigationEnd)
    .subscribe((event: any) => {
      console.log(event);
      // this.previousUrl = event.url;
    });
  }
  ...
}
dev_054
  • 3,448
  • 8
  • 29
  • 56
  • maybe use `NavigationStart` event? – Max Koretskyi Jul 16 '17 at 04:39
  • 1
    @Maximus the event isn't the problem. I just removed the `filter` completely and it doesn't return me the REAL url that it comes from. In fact, IMHO, it's too complicated to work with routes in Angular. A simple thing like take the last visited route is toooooo complicated. – dev_054 Jul 17 '17 at 00:47

1 Answers1

0

This is what happens, step-by-step:

  1. You are at /home/xxx
  2. You navigate to /home/unknown
  3. The router notices that you are on a path that should be redirected to /404, so it does that.
  4. You are at /404 and you check the previous URL which is /home/unknown.

I can think of 2 ways that this can be resolved:

  1. Instead of redirecting ** to /404, just set the 404 component to the path ** in the router. You will stay on /home/unknown with the 404 component.
  2. Implement a service of your own that tracks the url's visited in your application. For instance you could subscribe to the Location service from @angular/router, and track the URL's visited.
Mezo Istvan
  • 2,664
  • 1
  • 14
  • 17
  • Thanks for your answer, but it doesn't answer my question... I don't want my url to stay at `/home/unknown`, I just want to get the last (known) visited page, in this case, `home/xxx`. – dev_054 Jul 17 '17 at 00:48